fix(payments): never reuse a subaddress or count older payments toward an invoice

Subaddress indices wrapped after 300 invoices per merchant, and the
reconciler counted every transfer ever received on the subaddress. A later
invoice could therefore show as paid by an earlier invoice's payment.

Indices now only increase, and the reconciler counts only transfers whose
timestamp is no more than two hours before the invoice was created. The slack
covers Monero's block timestamp rules, so a genuine payment mined after
creation always counts.
This commit is contained in:
2026-11-18 15:37:34 -05:00
parent b44181d8d9
commit bdacfd278f
4 changed files with 149 additions and 12 deletions
+34
View File
@@ -0,0 +1,34 @@
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from typing import Iterable, TypeVar
# Monero accepts a block whose timestamp is above the median of the previous 60
# blocks (about an hour behind the chain tip) and at most two hours ahead of
# the node clock. A payment mined after an invoice was created can therefore
# carry a timestamp up to roughly an hour earlier than the invoice. Two hours
# keeps every genuine payment and still excludes anything older.
BLOCK_TIMESTAMP_SLACK = timedelta(hours=2)
T = TypeVar("T")
def transfers_for_invoice(transfers: Iterable[T], created_at: datetime | None) -> list[T]:
"""Return only the transfers that can belong to an invoice created at created_at.
A subaddress can carry payments that predate its current invoice: older
invoices reused it, or someone paid it before. Those must never count toward
the new invoice. A transfer with no timestamp is excluded once the invoice
has a creation time, because nothing proves it is recent.
"""
items = list(transfers)
if created_at is None:
return items
if created_at.tzinfo is None:
created_at = created_at.replace(tzinfo=timezone.utc)
cutoff = int((created_at - BLOCK_TIMESTAMP_SLACK).timestamp())
return [
item
for item in items
if getattr(item, "timestamp", None) is not None and int(item.timestamp) >= cutoff
]
+4 -2
View File
@@ -12,6 +12,7 @@ from sqlalchemy.orm import Session
from .btcpay_webhooks import dispatch_btcpay_webhooks
from .config import INVOICE_RECONCILE_INTERVAL_SECONDS, LATE_PAYMENT_LOOKBACK_HOURS
from .db import SessionLocal
from .invoice_transfers import transfers_for_invoice
from .models import Invoice, InvoiceTransfer, SystemStatus, User
from .monero_service import MoneroWalletService, TransferDetail
from .webhooks import dispatch_webhooks
@@ -127,8 +128,9 @@ def _reconcile_invoices(service: MoneroWalletService) -> None:
if not acquired:
continue
try:
transfers = _get_transfers_with_retry(
service, user, invoice.address,
transfers = transfers_for_invoice(
_get_transfers_with_retry(service, user, invoice.address),
invoice.created_at,
)
total_atomic = 0
+8 -10
View File
@@ -7,6 +7,8 @@ from .security import decrypt_secret
from .subaddress_derivation import derive_subaddress
# Caps how many donation invoices may be active at once. It no longer bounds
# subaddress indices, which only ever increase.
MAX_SUBADDRESS_INDEX = 300
@@ -26,17 +28,13 @@ def create_subaddress_for_user(
if locked is None:
raise ValueError("User not found")
start_index = int(locked.subaddress_start_index or 0)
if start_index < 0 or start_index >= MAX_SUBADDRESS_INDEX:
if start_index < 0:
start_index = 0
range_start = start_index + 1
range_end = MAX_SUBADDRESS_INDEX
next_index = int(locked.next_subaddress_index or range_start)
if next_index < range_start or next_index > range_end:
next_index = range_start
next_next_index = next_index + 1
if next_next_index > range_end:
next_next_index = range_start
locked.next_subaddress_index = next_next_index
# Indices only ever increase. Wrapping back to the start of a range made a
# later invoice share a subaddress with an earlier one, so the earlier
# invoice's payment counted toward the later invoice.
next_index = max(int(locked.next_subaddress_index or 0), start_index + 1)
locked.next_subaddress_index = next_index + 1
db.flush()
view_key = decrypt_secret(locked.view_key_encrypted)
address = derive_subaddress(
+103
View File
@@ -0,0 +1,103 @@
import unittest
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from unittest import mock
from app import subaddress_allocator
from app.invoice_transfers import transfers_for_invoice
@dataclass
class _Transfer:
txid: str
amount_atomic: int
timestamp: int | None
class _User:
def __init__(self, start_index=0, next_index=1):
self.id = "user"
self.subaddress_start_index = start_index
self.next_subaddress_index = next_index
self.view_key_encrypted = "encrypted"
self.payment_address = "address"
class _Query:
def __init__(self, user):
self._user = user
def filter(self, *args, **kwargs):
return self
def with_for_update(self):
return self
def first(self):
return self._user
class _Session:
def __init__(self, user):
self._user = user
def query(self, model):
return _Query(self._user)
def flush(self):
pass
def _allocate(user, count):
session = _Session(user)
with mock.patch.object(subaddress_allocator, "decrypt_secret", return_value="view"), \
mock.patch.object(
subaddress_allocator,
"derive_subaddress",
side_effect=lambda **kw: f"sub-{kw['address_index']}",
):
return [subaddress_allocator.create_subaddress_for_user(session, user=user)[1] for _ in range(count)]
class SubaddressAllocationTests(unittest.TestCase):
def test_indices_never_repeat_for_a_merchant(self):
indices = _allocate(_User(), 1000)
self.assertEqual(len(indices), len(set(indices)))
self.assertEqual(indices, sorted(indices))
def test_allocation_starts_after_the_merchant_start_index(self):
indices = _allocate(_User(start_index=500, next_index=1), 3)
self.assertTrue(all(index > 500 for index in indices))
def test_a_stored_next_index_beyond_the_old_range_is_kept(self):
indices = _allocate(_User(next_index=301), 2)
self.assertGreaterEqual(min(indices), 301)
class InvoiceTransferWindowTests(unittest.TestCase):
def setUp(self):
self.created = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc)
def _at(self, delta):
return int((self.created + delta).timestamp())
def test_a_payment_from_before_the_invoice_does_not_count(self):
old = _Transfer("old", 10, self._at(-timedelta(days=3)))
new = _Transfer("new", 5, self._at(timedelta(minutes=4)))
self.assertEqual([t.txid for t in transfers_for_invoice([old, new], self.created)], ["new"])
def test_a_block_timestamp_slightly_behind_the_invoice_still_counts(self):
lagging = _Transfer("lagging", 10, self._at(-timedelta(minutes=50)))
self.assertEqual(len(transfers_for_invoice([lagging], self.created)), 1)
def test_a_transfer_without_a_timestamp_does_not_count(self):
self.assertEqual(transfers_for_invoice([_Transfer("x", 10, None)], self.created), [])
def test_a_naive_creation_time_is_read_as_utc(self):
naive = self.created.replace(tzinfo=None)
old = _Transfer("old", 10, self._at(-timedelta(days=1)))
self.assertEqual(transfers_for_invoice([old], naive), [])
if __name__ == "__main__":
unittest.main()