core+gui+cli: anticipation/rebuild dates, preserve relative settings
Fixes around the delivery/build/check date handling (karen7 regtest):
- build_will (GUI + CLI) re-anchors date_to_check to the CURRENT heirs'
earliest future delivery before building, so an anticipated rebuild is no
longer blocked by the stale old-will anchor (NO_FUTURE_DATE). The checks of
the existing will keep their anchored date_to_check.
- _sync_locktime_to_built_txs now PRESERVES RELATIVE locktime/threshold
recipes ("2y"/"150d") in WILL_SETTINGS instead of freezing them to absolute
timestamps: the anchored comparisons (resolve_locktime_against_tx and
resolve_date_to_check with built_locktime) already prevent the daily
invalidate prompt. Absolute values still sync on a genuine automatic
anticipation.
- Will.remove_stale_wallet_history drops stale wallet-LOCAL will placeholders
before every (re)build in GUI and CLI so their coins are available again.
- check_willexecutors_and_heirs raises HeirNotFoundException outside the
count_heirs gate: a shortened relative recipe on a signed will now triggers
a plain rebuild ("no heirs" only when there really are none).
- is_locktime_below_threshold compares the settings on one reference frame
(resolve_guard_threshold), no longer against the built-will anchor.
Tests: purge unit + call-site, no-heirs, guard, anticipated-rebuild
end-to-end (GUI) + CLI mirror + fixed_percent_lists_amount unit,
relative-preserve sync; conftest restores electrum.constants.net after each
test (cross-file pollution guard).
This commit is contained in:
18
tests/conftest.py
Normal file
18
tests/conftest.py
Normal file
@@ -0,0 +1,18 @@
|
||||
"""Shared pytest fixtures.
|
||||
|
||||
Guards every test against cross-file network pollution: several karen7
|
||||
regtest modules historically flipped ``electrum.constants.net`` to regtest at
|
||||
import time, which broke unrelated offline tests (e.g. the CLI controller
|
||||
suite) run in the same pytest process.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from electrum import constants
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _restore_network():
|
||||
"""Snapshot ``constants.net`` before each test and restore it after."""
|
||||
prev = constants.net
|
||||
yield
|
||||
constants.net = prev
|
||||
@@ -18,6 +18,7 @@ import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest.mock as mock
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
|
||||
|
||||
@@ -25,6 +26,8 @@ from electrum.simple_config import SimpleConfig
|
||||
from electrum.util import UserFacingException
|
||||
|
||||
from bal.cli.controller import BalController
|
||||
from bal.core.heirs import Heirs
|
||||
from bal.core.util import Util
|
||||
|
||||
VALID_ADDRESS = "bc1qusymuetsz2psaqzqxv8qmzcy64d9meckj3lxxf"
|
||||
|
||||
@@ -227,6 +230,39 @@ def test_auto_rebuild_threshold_passed_invalidates():
|
||||
assert result["invalidation_tx"] == {"txid": None, "tx": None}
|
||||
|
||||
|
||||
def test_build_will_reanchors_date_to_check_to_new_locktime():
|
||||
"""CLI mirror of the GUI regression: ``build_will`` must re-anchor
|
||||
``date_to_check`` to the CURRENT heirs' earliest delivery before building,
|
||||
so an anticipated (shortened) rebuild is not blocked by the old built-will
|
||||
anchor (which would yield NO_FUTURE_DATE in ``get_transactions``).
|
||||
"""
|
||||
with Plugin() as plugin:
|
||||
plugin.USER_TYPE.set("advanced")
|
||||
plugin.NO_WILLEXECUTOR.set(True)
|
||||
plugin.ENABLE_MULTIVERSE.set(True)
|
||||
plugin.WILL_SETTINGS.set({"threshold": "150d", "locktime": "2y", "baltx_fees": 20})
|
||||
c = _make_controller(plugin)
|
||||
c.no_willexecutor = True
|
||||
c.heirs["alice"] = [VALID_ADDRESS, "100%", "1y"]
|
||||
|
||||
# Simulate an old built will frozen at 2y: reload keeps its (stale)
|
||||
# anchor, which would reject the anticipated "1y" delivery.
|
||||
c.init_class_variables()
|
||||
stale_anchor = Util.parse_locktime_string("2y") - 150 * 86400
|
||||
c.date_to_check = stale_anchor
|
||||
assert Util.parse_locktime_string("1y") < c.date_to_check
|
||||
|
||||
with mock.patch.object(Heirs, "get_transactions", return_value={}) as gt:
|
||||
result = c.build_will()
|
||||
|
||||
assert result == {}
|
||||
# build_will re-anchored date_to_check to the new 1y delivery...
|
||||
expected = Util.parse_locktime_string("1y") - 150 * 86400
|
||||
assert abs(c.date_to_check - expected) < 3600
|
||||
# ...and used THAT anchor as the build filter, not the stale 2y one.
|
||||
assert gt.call_args.args[-1] == c.date_to_check
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# runner
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
@@ -18,6 +18,7 @@ from bal.core.checkalive import ( # noqa: E402 (path insert above)
|
||||
CheckAliveError,
|
||||
check_alive_expired,
|
||||
resolve_date_to_check,
|
||||
resolve_guard_threshold,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
@@ -148,6 +149,76 @@ def test_advanced_mode_relative_locktime_without_built_tx_falls_back():
|
||||
assert abs(result - expected) < 1
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# resolve_guard_threshold
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
|
||||
def test_guard_threshold_basic_mode_returns_none():
|
||||
fake_now = 1_800_000_000.0
|
||||
threshold = resolve_guard_threshold(True, {"threshold": "30d"}, now=fake_now)
|
||||
assert threshold is None
|
||||
|
||||
|
||||
def _guard_locktime(settings, fake_now):
|
||||
"""Reproduce the call-site locktime expression of the guard."""
|
||||
from bal.core.plugin_base import BalTimestamp
|
||||
|
||||
return BalTimestamp(settings["locktime"]).to_timestamp(fake_now)
|
||||
|
||||
|
||||
def test_guard_threshold_absolute():
|
||||
fake_now = 1_800_000_000.0
|
||||
locktime = fake_now + 90 * 86400
|
||||
threshold = locktime - 30 * 86400
|
||||
settings = {"locktime": locktime, "threshold": threshold}
|
||||
assert resolve_guard_threshold(False, settings, now=fake_now) == threshold
|
||||
|
||||
|
||||
def test_guard_threshold_relative_fresh_anchor():
|
||||
"""A relative threshold must be anchored to the FRESH locktime so the
|
||||
guard and the settings always share one reference frame.
|
||||
|
||||
Regression for the false positive where a still-valid built will frozen at
|
||||
a LONGER delivery ("2y") anchored ``date_to_check`` beyond the currently
|
||||
stored shorter delivery ("1y"): the old guard compared the fresh "1y"
|
||||
locktime against that anchored threshold and wrongly fired "locktime is
|
||||
lower than threshold", even though the settings themselves are consistent
|
||||
(locktime is 30d AFTER the threshold).
|
||||
"""
|
||||
fake_now = 1_800_000_000.0
|
||||
settings = {"locktime": "1y", "threshold": "30d"}
|
||||
locktime = _guard_locktime(settings, fake_now)
|
||||
threshold = resolve_guard_threshold(False, settings, now=fake_now)
|
||||
assert threshold is not None
|
||||
assert locktime > threshold # internally consistent: no fire
|
||||
assert threshold > fake_now
|
||||
# The helper takes no built anchor: a frozen "2y" built will must NOT
|
||||
# contaminate the result, although resolve_date_to_check (the expiry
|
||||
# reference) legitimately keeps using it.
|
||||
frozen_two_years = locktime + 365 * 86400
|
||||
anchored = resolve_date_to_check(
|
||||
False, settings, now=fake_now, built_locktime=frozen_two_years
|
||||
)
|
||||
assert anchored > threshold # built anchor pushes date_to_check forward...
|
||||
assert locktime < anchored # ...which is exactly what used to fire the bug
|
||||
|
||||
|
||||
def test_guard_threshold_relative_locktime_absolute_threshold():
|
||||
fake_now = 1_800_000_000.0
|
||||
threshold = fake_now + 200 * 86400
|
||||
settings = {"locktime": "1y", "threshold": threshold}
|
||||
assert resolve_guard_threshold(False, settings, now=fake_now) == threshold
|
||||
# "1y" from now is later than the stored absolute threshold: allowed.
|
||||
locktime = _guard_locktime(settings, fake_now)
|
||||
assert locktime > threshold
|
||||
|
||||
|
||||
def test_guard_threshold_missing_returns_none():
|
||||
fake_now = 1_800_000_000.0
|
||||
assert resolve_guard_threshold(False, {"locktime": "1y"}, now=fake_now) is None
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# check_alive_expired
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
@@ -36,6 +36,7 @@ from bal.core.heirs import (
|
||||
is_op_return_address,
|
||||
validate_op_return_hex,
|
||||
)
|
||||
from bal.core.util import Util
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Constants
|
||||
@@ -167,6 +168,32 @@ def test_heirs_amount_to_float():
|
||||
assert heirs.amount_to_float("notanumber") == 0.0
|
||||
|
||||
|
||||
def test_fixed_percent_lists_uses_build_anchor_for_relative_heirs():
|
||||
"""A relative heir must survive the amount filter when the build anchor
|
||||
(``from_locktime``) is recalculated for the anticipated delivery.
|
||||
|
||||
Before the fix, ``build_will`` kept ``date_to_check`` anchored to the OLD
|
||||
(longer) built will; an "1y" heir resolved before that anchor was excluded
|
||||
by the ``cmp <= 0`` filter and the build reported NO_FUTURE_DATE. With the
|
||||
anchor recomputed for the new locktime (karen7: 2y -> 1y delivery) the
|
||||
"1y" heir is kept.
|
||||
"""
|
||||
wallet = FakeWallet()
|
||||
heirs = Heirs(wallet)
|
||||
heirs["carol"] = ["addr1", "100%", "1y"]
|
||||
|
||||
# Stale anchor (old built 2y will still frozen): "1y" is in the past
|
||||
# relative to it -> excluded from the amount calculation.
|
||||
stale_anchor = Util.parse_locktime_string("2y") - 150 * 86400
|
||||
_, _, percent_heirs, _, _ = heirs.fixed_percent_lists_amount(stale_anchor, 500)
|
||||
assert "carol" not in percent_heirs
|
||||
|
||||
# Recalculated anchor for the new (1y) delivery: the heir is retained.
|
||||
new_anchor = Util.parse_locktime_string("1y") - 150 * 86400
|
||||
_, _, percent_heirs, _, _ = heirs.fixed_percent_lists_amount(new_anchor, 500)
|
||||
assert "carol" in percent_heirs
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Validation (static methods)
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
@@ -13,8 +13,14 @@ import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
|
||||
|
||||
from bal.core.checkalive import resolve_date_to_check
|
||||
from bal.core.util import copy_structure
|
||||
from bal.core.will import Will, WillItem
|
||||
from bal.core.will import (
|
||||
HeirNotFoundException,
|
||||
NoHeirsException,
|
||||
Will,
|
||||
WillItem,
|
||||
)
|
||||
|
||||
# A valid serialized Bitcoin transaction hex (1 input + 1 P2PKH output, version 2)
|
||||
_VALID_TX_HEX = (
|
||||
@@ -210,6 +216,59 @@ def test_check_heir_added_triggers_rebuild():
|
||||
assert raised, "adding an heir must raise HeirNotFoundException"
|
||||
|
||||
|
||||
def test_shortened_relative_recipe_on_signed_rebuilds_not_noheirs():
|
||||
"""Regression (karen7): heirs shortened "2y"->"1y" on a signed will whose
|
||||
ADVANCED check window is anchored to the frozen built delivery must trigger
|
||||
a plain rebuild (HeirNotFoundException), NOT "No Heirs".
|
||||
|
||||
Earlier the count gate resolved each current relative recipe from *now*
|
||||
while ``check_date`` was anchored to the (longer) frozen built locktime, so
|
||||
every heir fell below the window and was silently excluded -> NoHeirs even
|
||||
though the will simply needs rebuilding on the new, shorter schedule."""
|
||||
lt = 2_100_000_000 # a far-future frozen delivery (a "2y" build)
|
||||
will_heirs = {"alice": ["addr_alice", 5000, "2y"]}
|
||||
current_heirs = {"alice": ["addr_alice", 5000, "1y"]}
|
||||
will = _make_will_with_heirs(will_heirs, lt)
|
||||
will["willid_1"].set_status("COMPLETE", True)
|
||||
check_date = resolve_date_to_check(
|
||||
False, {"locktime": "2y", "threshold": "150d"}, built_locktime=lt
|
||||
)
|
||||
assert check_date < lt # the anchored window really precedes the delivery
|
||||
raised = None
|
||||
try:
|
||||
Will.check_willexecutors_and_heirs(
|
||||
will, copy_structure(current_heirs), {}, False, check_date, 100
|
||||
)
|
||||
except HeirNotFoundException:
|
||||
raised = "rebuild"
|
||||
except NoHeirsException:
|
||||
raised = "noheirs"
|
||||
assert raised == "rebuild", (
|
||||
f"shortened recipe on a signed will must rebuild, got {raised!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_all_heirs_past_check_date_still_noheirs():
|
||||
"""The "no valid heirs" gate is preserved: when every heir is coherent with
|
||||
the built will but its delivery lies before ``check_date``, the check still
|
||||
reports NoHeirsException (there is literally nothing future to inherit)."""
|
||||
lt = 1_900_000_000
|
||||
will_heirs = {"alice": ["addr_alice", 5000, str(lt)]}
|
||||
will = _make_will_with_heirs(will_heirs, lt)
|
||||
raised = None
|
||||
try:
|
||||
Will.check_willexecutors_and_heirs(
|
||||
will, copy_structure(will_heirs), {}, False, lt + 86400, 100
|
||||
)
|
||||
except HeirNotFoundException:
|
||||
raised = "rebuild"
|
||||
except NoHeirsException:
|
||||
raised = "noheirs"
|
||||
assert raised == "noheirs", (
|
||||
f"a fully delivered will must report NoHeirs, got {raised!r}"
|
||||
)
|
||||
|
||||
|
||||
def test_needs_server_check():
|
||||
"""Check button selection logic: only a VALID, PUSHED will with a
|
||||
will-executor that is not yet CHECKED must be queried on the server.
|
||||
|
||||
@@ -450,6 +450,12 @@ class FakeADB:
|
||||
|
||||
def remove_transaction(self, txid):
|
||||
self.removed.append(txid)
|
||||
# Simulate the real adb: dropping a stored tx frees the outputs it spent.
|
||||
for utxos in self.outputs.values():
|
||||
for utxo in utxos.values():
|
||||
if getattr(utxo, "spent_txid", None) == txid:
|
||||
utxo.spent_txid = None
|
||||
utxo.spent_height = None
|
||||
|
||||
def get_spender(self, outpoint):
|
||||
txid = self.spenders.get(outpoint)
|
||||
@@ -837,6 +843,73 @@ def test_get_available_utxos_none_locktime_is_raw_view():
|
||||
assert Util.get_available_utxos(None, _HISTORY_TEMPLATE, 1000) == []
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Will.remove_stale_wallet_history (pre-build history purge)
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def test_remove_stale_wallet_history_frees_equal_locktime_spend():
|
||||
# The stale placeholders (saved by a previous prepare) have the SAME
|
||||
# locktime as the will being rebuilt, so get_available_utxos does NOT
|
||||
# restore their coins (see test_...does_not_restore_not_later_locktime).
|
||||
# The pre-build purge deletes them and the coins become available again.
|
||||
wallet, utxo = _wallet_with_local_spend(locktime=1000)
|
||||
spender = "ab" * 32
|
||||
assert Util.get_available_utxos(wallet, _HISTORY_TEMPLATE, 1000) == []
|
||||
removed = Will.remove_stale_wallet_history(wallet, _HISTORY_TEMPLATE)
|
||||
assert removed == [spender]
|
||||
assert wallet.adb.removed == [spender]
|
||||
assert spender not in wallet.labels
|
||||
assert [
|
||||
u.prevout.to_str()
|
||||
for u in Util.get_available_utxos(wallet, _HISTORY_TEMPLATE, 1000)
|
||||
] == [utxo.prevout.to_str()]
|
||||
|
||||
|
||||
def test_remove_stale_wallet_history_keeps_confirmed_spender():
|
||||
# A broadcast (confirmed) BAL-labelled tx is never purged.
|
||||
addr = "bcrt1qexample"
|
||||
spender = "ab" * 32
|
||||
utxo = _make_utxo(spent_txid=spender, spent_height=100)
|
||||
wallet = FakeWallet(
|
||||
stored_txs={spender: _make_multisig_ptx(0, locktime=2000)},
|
||||
heights={spender: 100},
|
||||
outputs={addr: {utxo.prevout.to_str(): utxo}},
|
||||
addresses=[addr],
|
||||
)
|
||||
wallet.labels[spender] = _HISTORY_LABEL
|
||||
removed = Will.remove_stale_wallet_history(wallet, _HISTORY_TEMPLATE)
|
||||
assert removed == []
|
||||
assert wallet.adb.removed == []
|
||||
assert wallet.labels[spender] == _HISTORY_LABEL
|
||||
|
||||
|
||||
def test_remove_stale_wallet_history_keeps_unlabeled_local_spender():
|
||||
# Wallet-local BAL-status tx without a matching history label stays.
|
||||
wallet, _ = _wallet_with_local_spend(locktime=1000)
|
||||
spender = "ab" * 32
|
||||
wallet.labels[spender] = "some other label"
|
||||
removed = Will.remove_stale_wallet_history(wallet, _HISTORY_TEMPLATE)
|
||||
assert removed == []
|
||||
assert wallet.adb.removed == []
|
||||
assert wallet.labels[spender] == "some other label"
|
||||
|
||||
|
||||
def test_remove_stale_wallet_history_noop_without_wallet_or_adb():
|
||||
assert Will.remove_stale_wallet_history(None, _HISTORY_TEMPLATE) == []
|
||||
wallet = FakeWallet()
|
||||
wallet.adb = None
|
||||
assert Will.remove_stale_wallet_history(wallet, _HISTORY_TEMPLATE) == []
|
||||
|
||||
|
||||
def test_remove_stale_wallet_history_never_raises():
|
||||
adb = MagicMock()
|
||||
adb.get_tx_height.side_effect = RuntimeError("boom")
|
||||
wallet = MagicMock()
|
||||
wallet.adb = adb
|
||||
wallet.get_all_labels.return_value = {"ab" * 32: _HISTORY_LABEL}
|
||||
assert Will.remove_stale_wallet_history(wallet, _HISTORY_TEMPLATE) == []
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Main
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
@@ -179,6 +179,7 @@ def test_rebuild_path_schedules_full_refresh():
|
||||
win.date_to_check = 1_800_000_000
|
||||
win.will_settings = {"baltx_fees": 1, "locktime": "1 month"}
|
||||
win.bal_plugin = _CfgBag(
|
||||
is_basic_mode=lambda: False,
|
||||
MAX_WILLEXECUTOR_FEE=_Cfg(1),
|
||||
SAVE_HISTORY=_Cfg(True),
|
||||
HISTORY_LABEL=_Cfg("LBL"),
|
||||
@@ -204,6 +205,46 @@ def test_rebuild_path_schedules_full_refresh():
|
||||
schedule_mock.assert_called_once_with()
|
||||
|
||||
|
||||
def test_rebuild_purges_stale_wallet_history_before_building():
|
||||
# The rebuild path must drop stale wallet-LOCAL will placeholders (saved by
|
||||
# an earlier prepare) so their coins are available to the new build.
|
||||
win = object.__new__(BalWindow)
|
||||
win.disable_plugin = False
|
||||
win.heirs = {"h": object()}
|
||||
win.willexecutors = {}
|
||||
win.no_willexecutor = True
|
||||
win.willitems = {}
|
||||
win.will = {}
|
||||
win.date_to_check = 1_800_000_000
|
||||
win.will_settings = {"baltx_fees": 1, "locktime": "1 month"}
|
||||
win.bal_plugin = _CfgBag(
|
||||
is_basic_mode=lambda: False,
|
||||
MAX_WILLEXECUTOR_FEE=_Cfg(1),
|
||||
SAVE_HISTORY=_Cfg(True),
|
||||
HISTORY_LABEL=_Cfg("LBL"),
|
||||
)
|
||||
win.window = _FakeWindow()
|
||||
win.window.wallet = _Wallet()
|
||||
with (
|
||||
patch.object(Util, "get_available_utxos", return_value=[]),
|
||||
patch.object(Util, "parse_locktime_string", return_value=1_800_000_001),
|
||||
patch.object(Will, "get_min_locktime", return_value=0),
|
||||
patch.object(Will, "check_amounts"),
|
||||
patch.object(BalWindow, "init_class_variables"),
|
||||
patch.object(BalWindow, "build_will"),
|
||||
patch.object(
|
||||
BalWindow,
|
||||
"check_will",
|
||||
side_effect=[NotCompleteWillException(), None],
|
||||
),
|
||||
patch.object(BalWindow, "update_all"),
|
||||
patch.object(BalWindow, "_schedule_history_refresh"),
|
||||
patch.object(Will, "remove_stale_wallet_history") as purge_mock,
|
||||
):
|
||||
BalWindow.build_inheritance_transaction(win)
|
||||
purge_mock.assert_called_once_with(win.window.wallet, "LBL")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Main
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
@@ -390,6 +390,110 @@ def test_insufficient_funds_warns():
|
||||
assert not ctl.willitems
|
||||
|
||||
|
||||
def test_guard_not_blocked_by_old_built_will():
|
||||
"""Regression: shortening the delivery in the STORED settings (relative
|
||||
"1y"/"30d") while an old, still-VALID built will is frozen at a longer
|
||||
locktime must NOT fire the "locktime is lower than threshold" guard.
|
||||
|
||||
The old guard compared the fresh settings locktime against ``date_to_check``
|
||||
anchored to the built will (see ``resolve_date_to_check``), so a built-will
|
||||
delivery longer than the settings' one made it fire even though the settings
|
||||
are internally consistent (locktime is 30d AFTER the threshold). The guard
|
||||
must instead compare the stored settings on a single reference frame
|
||||
(``BalWindow.is_locktime_below_threshold``); ``date_to_check`` keeps its
|
||||
built anchor for the expiry/validity checks.
|
||||
"""
|
||||
with _no_willexecutors():
|
||||
ctl = make_controller()
|
||||
ctl.bal_plugin.USER_TYPE.set("advanced") # ADVANCED Check-Alive mode
|
||||
ctl.prepare_will()
|
||||
txid, item = _single(ctl)
|
||||
|
||||
# Freeze the built (VALID) will at a delivery one year longer than the
|
||||
# now-shortened settings: the pre-fix guard would reject the rebuild.
|
||||
item.tx.locktime = item.tx.locktime + 365 * 86400
|
||||
ctl.will_settings = {"locktime": "1y", "threshold": "30d"}
|
||||
Util.fix_will_settings_tx_fees(ctl.will_settings)
|
||||
|
||||
ctl.init_class_variables()
|
||||
|
||||
# date_to_check is anchored to the built will (long delivery)...
|
||||
assert ctl.date_to_check == item.tx.locktime - 30 * 86400
|
||||
# ...and the OLD guard would have fired here:
|
||||
old_locktime = Util.parse_locktime_string(ctl.will_settings["locktime"])
|
||||
assert old_locktime < ctl.date_to_check
|
||||
# but the settings themselves are consistent, so the guard must pass:
|
||||
assert ctl.is_locktime_below_threshold() is False
|
||||
assert not ctl.window.errors
|
||||
|
||||
|
||||
def test_anticipated_rebuild_reanchors_date_to_check():
|
||||
"""Regression (karen7): rebuilding a SIGNED will whose delivery was
|
||||
anticipated (per-heir recipes shortened from 2y to 1y, ADVANCED mode) must
|
||||
succeed.
|
||||
|
||||
``date_to_check`` stays anchored to the OLD built delivery for the validity
|
||||
checks, but ``build_will`` must re-anchor it to the NEW (earliest current)
|
||||
delivery as its build filter: before the fix the stale 2028 anchor rejected
|
||||
every "1y" heir (cmp <= 0 in ``fixed_percent_lists_amount``) and the build
|
||||
reported ``NO_FUTURE_DATE``. The old signed item is then superseded by
|
||||
``search_rai`` (REPLACED -> no on-chain invalidation) and the rebuilt will
|
||||
is coherent again.
|
||||
"""
|
||||
with _no_willexecutors():
|
||||
ctl = make_controller()
|
||||
ctl.bal_plugin.USER_TYPE.set("advanced")
|
||||
# Per-heir deliveries require multiverse mode (the only way heirs can
|
||||
# carry a different recipe than the settings locktime).
|
||||
ctl.bal_plugin.ENABLE_MULTIVERSE.set(True)
|
||||
ctl.will_settings = {"locktime": "2y", "threshold": "150d", "baltx_fees": 20}
|
||||
Util.fix_will_settings_tx_fees(ctl.will_settings)
|
||||
ctl.heirs["alice"][2] = "2y"
|
||||
ctl.heirs["bob"][2] = "2y"
|
||||
|
||||
# Build and sign a 2y will (the old, committed delivery).
|
||||
ctl.prepare_will()
|
||||
old_txid, _old_item = _single(ctl)
|
||||
old_locktime = _old_item.tx.locktime
|
||||
signed = ctl.sign_transactions(None)
|
||||
_old_item.tx = Will.get_tx_from_any(str(signed[old_txid]))
|
||||
Will.check_signatures(ctl.willitems, ctl.wallet)
|
||||
assert _old_item.get_status("COMPLETE")
|
||||
|
||||
# Anticipate: shorten every heir to 1y.
|
||||
ctl.heirs["alice"][2] = "1y"
|
||||
ctl.heirs["bob"][2] = "1y"
|
||||
|
||||
ctl.init_class_variables()
|
||||
# date_to_check stays anchored to the OLD built delivery...
|
||||
assert ctl.date_to_check == old_locktime - 150 * 86400
|
||||
# ...and that stale anchor would reject the anticipated "1y" dates.
|
||||
assert Util.parse_locktime_string("1y") < ctl.date_to_check
|
||||
|
||||
# The rebuild must succeed (re-anchored to the new delivery).
|
||||
willitems = ctl.build_inheritance_transaction()
|
||||
|
||||
assert ctl.heirs.last_build_error is None, "NO_FUTURE_DATE must not fire"
|
||||
new_valid = [
|
||||
it for tid, it in willitems.items()
|
||||
if tid != old_txid and it.get_status("VALID")
|
||||
]
|
||||
assert new_valid, "the anticipated (1y) will must build and stay VALID"
|
||||
new_item = new_valid[0]
|
||||
assert new_item.tx.locktime < old_locktime, "delivery must be anticipated"
|
||||
# date_to_check was re-anchored to the rebuilt delivery (1y minus 150d).
|
||||
assert abs(ctl.date_to_check - (new_item.tx.locktime - 150 * 86400)) < 3600
|
||||
|
||||
# The old signed item is kept but superseded (REPLACED -> not VALID).
|
||||
assert _old_item.get_status("REPLACED") is True
|
||||
assert _old_item.get_status("VALID") is False
|
||||
|
||||
# The rebuilt will is coherent (plain rebuild, no on-chain invalidation).
|
||||
assert ctl.check_will() is True
|
||||
assert not any("delivery date" in m for m in ctl.window.messages)
|
||||
assert not ctl.window.errors
|
||||
|
||||
|
||||
def _run_all():
|
||||
tests = [fn for name, fn in sorted(globals().items()) if name.startswith("test_")]
|
||||
for fn in tests:
|
||||
|
||||
@@ -18,9 +18,10 @@ The two gates that produced the prompt are covered here:
|
||||
never read as EXPIRED because the check window drifts past the frozen
|
||||
tx locktime.
|
||||
|
||||
The karen7 regtest wallet fixture (``tests/karen7``) reproduces the exact
|
||||
reported state: heirs with ``"1y"``, a signed/pushed/checked item whose frozen
|
||||
tx.locktime is 2027-08-05 (built 2026-08-05), and will_settings
|
||||
The reported state (reproduced hermetically here — the original live wallet
|
||||
dump ``tests/karen7`` is gitignored and regenerated as the wallet evolves) is:
|
||||
heirs with ``"1y"``, a signed/pushed/checked item whose frozen tx.locktime is
|
||||
2027-08-05 (built 2026-08-05), and will_settings
|
||||
``{"locktime": "2y", "threshold": "150d"}``.
|
||||
|
||||
Run:
|
||||
@@ -28,16 +29,14 @@ Run:
|
||||
python3 tests/test_heir_relative_anchor.py
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
|
||||
|
||||
import pytest # noqa: E402 (path insert above)
|
||||
from electrum import constants # noqa: E402 (path insert above)
|
||||
|
||||
constants.net = constants.BitcoinRegtest
|
||||
|
||||
from bal.core.checkalive import resolve_date_to_check # noqa: E402
|
||||
from bal.core.util import copy_structure # noqa: E402
|
||||
from bal.core.will import ( # noqa: E402
|
||||
@@ -49,6 +48,16 @@ from bal.core.will import ( # noqa: E402
|
||||
WillPostponedException,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _regtest_net():
|
||||
"""Run these regtest-focused tests with BitcoinRegtest, restoring mainnet
|
||||
afterwards so sibling test modules are unaffected by the net switch."""
|
||||
constants.net = constants.BitcoinRegtest
|
||||
yield
|
||||
constants.net = constants.BitcoinMainnet
|
||||
|
||||
|
||||
# A valid serialized tx (1 input + 1 output, version 2). Its nLockTime is 0;
|
||||
# the tests override ``tx.locktime`` to simulate the frozen signed locktime.
|
||||
_VALID_TX_HEX = (
|
||||
@@ -158,55 +167,52 @@ def test_absolute_postpone_on_signed_still_detected():
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# karen7 wallet regression (real fixture)
|
||||
# karen7 regression (hermetic, no live wallet fixture)
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
|
||||
def _load_karen7():
|
||||
path = os.path.join(os.path.dirname(__file__), "karen7")
|
||||
with open(path) as f:
|
||||
return json.load(f)
|
||||
# karen7's reported state, reproduced hermetically: heirs "1y", a signed item
|
||||
# frozen at delivery 2027-08-05 (built 2026-08-05), will_settings with a
|
||||
# relative "150d" delivery window and a "2y" promised locktime.
|
||||
_WILL_SETTINGS = {"locktime": "2y", "threshold": "150d"}
|
||||
|
||||
|
||||
def test_karen7_frozen_delivery_not_expired():
|
||||
"""ADVANCED date_to_check anchored to the frozen tx locktime: the check
|
||||
window opens BEFORE the delivery, so the will is never read as expired."""
|
||||
data = _load_karen7()
|
||||
will_settings = data["will_settings"]
|
||||
valid_wid = "28b64bfd83878d15c668473aa695a2b9bc23196bc61ab3149e8f33241826978d"
|
||||
wi = WillItem(data["will"][valid_wid], _id=valid_wid)
|
||||
built_locktime = Will.get_min_locktime({valid_wid: wi})
|
||||
heirs = {"alice": ["addr_alice", 5000, "1y"]}
|
||||
item = _make_will_item(copy_structure(heirs), _FROZEN, status_complete=True)
|
||||
will = {"willid_1": item}
|
||||
built_locktime = Will.get_min_locktime(will)
|
||||
assert built_locktime is not None
|
||||
assert built_locktime == int(wi.tx.locktime)
|
||||
assert built_locktime == int(item.tx.locktime)
|
||||
|
||||
date_to_check = resolve_date_to_check(
|
||||
False, will_settings, now=1_800_000_000.0, built_locktime=built_locktime
|
||||
False, _WILL_SETTINGS, now=1_800_000_000.0, built_locktime=built_locktime
|
||||
)
|
||||
assert int(date_to_check) < built_locktime
|
||||
# Re-evaluated 10 days later the window is identical (no daily drift).
|
||||
later = resolve_date_to_check(
|
||||
False, will_settings, now=1_800_000_000.0 + 10 * 86400,
|
||||
False, _WILL_SETTINGS, now=1_800_000_000.0 + 10 * 86400,
|
||||
built_locktime=built_locktime,
|
||||
)
|
||||
assert date_to_check == later
|
||||
|
||||
|
||||
def test_karen7_unchanged_heirs_are_coherent():
|
||||
"""The karen7 heirs (unchanged relative "2d") are coherent with the frozen
|
||||
signed tx: the plugin must NOT ask to invalidate the will."""
|
||||
data = _load_karen7()
|
||||
valid_wid = "28b64bfd83878d15c668473aa695a2b9bc23196bc61ab3149e8f33241826978d"
|
||||
"""Unchanged relative "1y" heirs are coherent with the frozen signed tx:
|
||||
the plugin must NOT ask to invalidate the will."""
|
||||
heirs = {"alice": ["addr_alice", 5000, "1y"]}
|
||||
# Use _FROZEN (a UTC-midnight value) so the check is compatible with
|
||||
# the UTC anchoring code.
|
||||
frozen_locktime = _FROZEN
|
||||
date_to_check = resolve_date_to_check(
|
||||
False, data["will_settings"],
|
||||
False, _WILL_SETTINGS,
|
||||
now=1_800_000_000.0,
|
||||
built_locktime=frozen_locktime,
|
||||
)
|
||||
outcome = _run_heir_check(
|
||||
data["will"][valid_wid]["heirs"],
|
||||
data["heirs"],
|
||||
copy_structure(heirs),
|
||||
copy_structure(heirs),
|
||||
frozen_locktime,
|
||||
status_complete=True,
|
||||
)
|
||||
@@ -219,6 +225,7 @@ def test_karen7_unchanged_heirs_are_coherent():
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
if __name__ == "__main__":
|
||||
constants.net = constants.BitcoinRegtest
|
||||
for name in sorted(dir()):
|
||||
if name.startswith("test_"):
|
||||
globals()[name]()
|
||||
|
||||
@@ -2,13 +2,17 @@
|
||||
Tests for ``BalBuildWillDialog._sync_locktime_to_built_txs``.
|
||||
|
||||
This is the post-build sync that keeps the plugin's stored delivery date
|
||||
(WILL_SETTINGS["locktime"]) and check-alive threshold in lockstep with the
|
||||
BUILT transactions' fixed locktime. The bug it fixes (reported by the owner):
|
||||
(WILL_SETTINGS["locktime"]) in lockstep with the BUILT transactions' fixed
|
||||
locktime when the core AUTOMATICALLY anticipates it (one day earlier than
|
||||
stored).
|
||||
|
||||
ADVANCED mode + RELATIVE locktime ("90d") / threshold ("30d") -> the plugin
|
||||
asks to invalidate the will EVERY DAY. The relative value is re-parsed
|
||||
against "now" on every check, so it drifts one day per day away from the
|
||||
fixed tx locktime and the postpone check always sees a "postpone".
|
||||
RELATIVE recipes ("90d" / "1y") are now PRESERVED: the daily-drift problem
|
||||
that once forced freezing them to absolute timestamps is solved at the root by
|
||||
anchoring every relative recipe against the built transactions
|
||||
(``Util.resolve_locktime_against_tx`` for the postpone detection,
|
||||
``resolve_date_to_check(..., built_locktime=...)`` for the reference
|
||||
timestamp). Only a genuine automatic anticipation on an ABSOLUTE stored date
|
||||
moves the stored value.
|
||||
|
||||
The method is exercised with a lightweight fake ``self`` (no Qt event loop, no
|
||||
Electrum wallet) by calling it as an unbound method.
|
||||
@@ -24,7 +28,6 @@ from types import SimpleNamespace
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir))
|
||||
|
||||
from bal.core.plugin_base import BalTimestamp # noqa: E402 (path insert above)
|
||||
from bal.gui.qt.dialogs import BalBuildWillDialog # noqa: E402 (path insert above)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
@@ -68,34 +71,30 @@ def _call_sync(will_settings, tx_locktimes, recorded):
|
||||
# Tests
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def test_relative_locktime_normalized_to_absolute():
|
||||
"""The reported bug: a relative stored locktime is frozen to the absolute
|
||||
value of the built transaction, even when it parses to the same moment."""
|
||||
def test_relative_locktime_preserved():
|
||||
"""A RELATIVE stored locktime ("90d"/"1y") is PRESERVED after a rebuild:
|
||||
it is anchored against the built transactions on every check, so it must
|
||||
not be frozen to an absolute timestamp in WILL_SETTINGS."""
|
||||
tx_locktime = 1_800_000_000
|
||||
recorded = []
|
||||
fake = _call_sync(
|
||||
{"locktime": "90d", "threshold": "30d"}, [tx_locktime], recorded
|
||||
)
|
||||
assert fake.bal_window.will_settings["locktime"] == tx_locktime
|
||||
assert fake.bal_window.will_settings["locktime"] != "90d"
|
||||
# A pure relative->absolute normalisation is NOT an anticipation: the sign
|
||||
# prompt must not claim the date was anticipated.
|
||||
assert fake.bal_window.will_settings["locktime"] == "90d"
|
||||
assert fake.bal_window.will_settings["threshold"] == "30d"
|
||||
assert recorded == [], "a relative recipe must never be rewritten"
|
||||
assert fake._date_was_anticipated is False
|
||||
|
||||
|
||||
def test_relative_threshold_frozen_to_absolute():
|
||||
"""A relative threshold ("N days BEFORE the delivery") is normalised to the
|
||||
same absolute value the settings widget computes (real_threshold)."""
|
||||
def test_relative_threshold_preserved():
|
||||
"""Same for the relative "Check Alive" threshold: it stays relative."""
|
||||
tx_locktime = 1_800_000_000
|
||||
recorded = []
|
||||
fake = _call_sync(
|
||||
{"locktime": "90d", "threshold": "30d"}, [tx_locktime], recorded
|
||||
)
|
||||
expected = int(
|
||||
BalTimestamp("30d").to_date(tx_locktime, reverse=True).timestamp()
|
||||
)
|
||||
assert fake.bal_window.will_settings["threshold"] == expected
|
||||
assert ("threshold", expected, True) in recorded
|
||||
assert fake.bal_window.will_settings["threshold"] == "30d"
|
||||
assert recorded == []
|
||||
|
||||
|
||||
def test_absolute_locktime_unchanged_on_equal():
|
||||
@@ -113,8 +112,8 @@ def test_absolute_locktime_unchanged_on_equal():
|
||||
|
||||
|
||||
def test_anticipation_sets_flag_and_moves_earlier():
|
||||
"""A real anticipation (built locktime earlier than the stored absolute
|
||||
one) still moves the date earlier and flags the sign prompt."""
|
||||
"""A real automatic anticipation of an ABSOLUTE stored date (built earlier
|
||||
than stored) still moves the date earlier and flags the sign prompt."""
|
||||
tx_locktime = 1_700_000_000
|
||||
recorded = []
|
||||
fake = _call_sync(
|
||||
@@ -129,7 +128,7 @@ def test_anticipation_sets_flag_and_moves_earlier():
|
||||
def test_stored_earlier_than_built_never_moved_later():
|
||||
"""A stored absolute date that is already EARLIER than the built txs (the
|
||||
user moved the delivery later) is never pulled back up on rebuild: only
|
||||
anticipation (built < stored) and relative normalisation move the value."""
|
||||
anticipation (built < stored) moves the value."""
|
||||
stored = 1_800_000_000
|
||||
recorded = []
|
||||
fake = _call_sync(
|
||||
@@ -142,39 +141,39 @@ def test_stored_earlier_than_built_never_moved_later():
|
||||
|
||||
|
||||
def test_multiple_txs_uses_minimum_locktime():
|
||||
"""When several transactions carry different locktimes, the minimum is used
|
||||
(owner-confirmed behaviour for the delivery date shown in the UI)."""
|
||||
"""When several ABSOLUTE transactions carry different locktimes, the minimum
|
||||
is used for a genuine automatic anticipation (owner-confirmed behaviour for
|
||||
the delivery date shown in the UI)."""
|
||||
min_locktime = 1_750_000_000
|
||||
recorded = []
|
||||
fake = _call_sync(
|
||||
{"locktime": "90d", "threshold": "30d"},
|
||||
{"locktime": 1_800_000_000, "threshold": 1_600_000_000},
|
||||
[min_locktime, min_locktime + 86_400],
|
||||
recorded,
|
||||
)
|
||||
assert fake.bal_window.will_settings["locktime"] == min_locktime
|
||||
|
||||
|
||||
def test_relative_locktime_stops_daily_postpone():
|
||||
"""End-to-end guard for the reported bug: after the sync, re-parsing the
|
||||
stored (now absolute) locktime on later days always equals the built
|
||||
tx locktime, so the postpone check never fires again."""
|
||||
from datetime import datetime, timedelta
|
||||
def test_relative_locktime_stays_coherent_via_anchor():
|
||||
"""Daily-drift guard: an UNCHANGED relative recipe is resolved against the
|
||||
tx build moment (``Util.resolve_locktime_against_tx``), so even WITHOUT
|
||||
being frozen to an absolute value it still reads as COHERENT (== tx
|
||||
locktime) on later days - the postpone check never fires again."""
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from bal.core.util import Util
|
||||
|
||||
tx_locktime = 1_800_000_000
|
||||
recorded = []
|
||||
fake = _call_sync(
|
||||
{"locktime": "90d", "threshold": "30d"}, [tx_locktime], recorded
|
||||
)
|
||||
stored = fake.bal_window.will_settings["locktime"]
|
||||
# resolve_locktime_against_tx normalises to UTC midnight before anchoring,
|
||||
# so use a midnight-UTC frozen tx locktime (the timestamp the engine itself
|
||||
# stores after building).
|
||||
tx_locktime = int(datetime(2027, 1, 15, tzinfo=timezone.utc).timestamp())
|
||||
built = "90d" # recipe frozen at build time
|
||||
current = "90d" # unchanged recipe today
|
||||
for _day in range(0, 7):
|
||||
# Simulate the check on later days: parse the STORED value (which is
|
||||
# now the absolute tx locktime) and compare with the fixed tx locktime.
|
||||
new_locktime = Util.parse_locktime_string(stored)
|
||||
assert new_locktime == tx_locktime
|
||||
assert new_locktime <= tx_locktime # no POSTPONE / drift
|
||||
# Sanity: a RELATIVE value would have drifted past it (the bug).
|
||||
resolved = Util.resolve_locktime_against_tx(current, built, tx_locktime)
|
||||
assert resolved == tx_locktime # no POSTPONE / drift
|
||||
# Sanity: a naive forward-from-now re-parse would have drifted past it
|
||||
# (the bug the anchor fixes).
|
||||
drifted = int(
|
||||
(
|
||||
datetime.fromtimestamp(tx_locktime) + timedelta(days=1)
|
||||
|
||||
Reference in New Issue
Block a user