"""Send To Many amount validation (the Nov 4 2026 theft: a huge first amount flips
signs at the tally step, draining receiver 0 into the sender). The three real payloads
must be rejected, honest multi-sends must still pass, and the shipped patch
must contain the per-receiver range + overflow check."""
from pathlib import Path

MAX_INT_8 = 2**63 - 1
ROOT = Path(__file__).resolve().parents[1]

EXPLOITS = [  # raw OP_RETURN payloads from the chain (after 6a1f)
    "6f6d6e6900000007000000270200fffffea49ddeb800010000015b62214801",
    "6f6d6e6900000007000000270200fffffe8d92fa244001000001726d05dbc1",
    "6f6d6e6900000007000000270200fffffb213c1d6dcc01000004dec3e29235",
]


def parse(hexpayload):
    b = bytes.fromhex(hexpayload)
    n = b[12]
    entries = [(b[13 + i * 9], int.from_bytes(b[14 + i * 9:22 + i * 9], "big")) for i in range(n)]
    n_value = sum(a for _, a in entries) % 2**64  # interpret_ wraps like C++ uint64
    return n_value, entries


def old_rule(n_value, entries, balance):
    total = sum(a for _, a in entries) % 2**64
    return 0 < n_value <= MAX_INT_8 and balance >= n_value and total == n_value


def fixed_rule(n_value, entries, balance):
    if not old_rule(n_value, entries, balance):
        return False
    total = 0
    for _, a in entries:
        if a == 0 or a > MAX_INT_8 or total > MAX_INT_8 - a:
            return False
        total += a
    return True


def test_old_code_accepted_the_real_exploits():
    for p in EXPLOITS:
        assert old_rule(*parse(p), balance=1)


def test_fixed_code_rejects_the_real_exploits():
    for p in EXPLOITS:
        assert not fixed_rule(*parse(p), balance=10**18)


def test_stolen_tsd_total_is_84377_826565():
    fake = sum(2**64 - parse(p)[1][0][1] for p in EXPLOITS)
    assert fake == 8437782656500


def test_honest_multisend_still_passes():
    entries = [(0, 1050000000), (1, 50000000)]
    assert fixed_rule(1100000000, entries, balance=1100000000)


def test_zero_amount_receiver_rejected():
    assert not fixed_rule(100, [(0, 100), (1, 0)], balance=100)


def test_patch_contains_check():
    # Auditor's v0.26.2 replacement (sha256 147a4780...).
    text = (ROOT / "stm-amount-fix-v0.26.2.patch").read_text()
    assert "amount == 0 || MAX_INT_8_BYTES < amount" in text
    assert "totalAmount > MAX_INT_8_BYTES - amount" in text
    assert "+#define DB_VERSION 10" in text  # forces every upgraded node to recount
    assert "Receiver amount is zero or above the maximum" in text  # thefts kept on record
    assert "+define(_CLIENT_VERSION_REVISION, 2)" in text
    assert "+#define OMNICORE_VERSION_MAJOR       1" in text


def test_obsolete_full_patch_removed():
    assert not (ROOT / "send-to-many.patch").exists()
