Skip to content

fix(send): refuse to send an invoice that already expired - #705

Merged
islandbitcoin merged 9 commits into
mainfrom
fix/expired-invoice-guard
Aug 20, 2026
Merged

islandbitcoin merged 9 commits into
mainfrom
fix/expired-invoice-guard

Conversation

@bobodread876

@bobodread876 bobodread876 commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes ENG-555.

The bug

Flash IBEX receive invoices live 60 seconds — IBEX caps non-msat accounts there (IBEX_RECEIVE_MAX_EXPIRATION_SECONDS, ENG-427). Decoding the invoice from the incident confirms it:

issued  1787243982  2026-08-20T16:39:42Z
expires 1787244042  2026-08-20T16:40:42Z   → exactly 60s

The confirmation screen holds whatever invoice was minted when the user left the amount screen, and resubmits it on every tap. In the reported case the identical paymentRequest was sent twice, 19 minutes apart:

16:40:04Z  attempt 1 — 38s before expiry → genuinely inside the window
16:58:52Z  attempt 2 — ~18 min past expiry → could never have succeeded

Both rendered as the same generic "Something went wrong". Because the user changed the amount between them, the amount looked like the variable under test when it was irrelevant — the investigation went after the wrong cause for a full round.

The fix

Check the held invoice's expiry before spending a round trip on a doomed send, and name what happened.

Design notes:

  • The check is scoped to invoices that actually get transmitted. Most sends put the held bolt11 on the wire, but the Breez/Spark BTC wallet's LNURL and intraledger paths do not: useSendPayment routes those to payLnurlBreez, which re-resolves the lightning address and mints a brand-new invoice at send time. Refusing on a stale held invoice there would kill a payment Breez would have completed. willTransmitHeldInvoice gates the guard; BTC + lightning still qualifies, because payLightningBreez is handed the detail's destination, which is the held bolt11.
  • The message depends on who minted the invoice. Only an LNURL send can honour "go back and get a fresh one" — the details screen re-mints on the way forward. A scanned or pasted bolt11 is fixed: setAmount returns the same invoice, and an amount-carrying invoice has no amount field to re-enter at all. Those users get the existing SendBitcoinDestinationScreen.expiredInvoice ("This invoice has expired. Please generate a new invoice.") instead.
  • Expiry is read off the invoice, but now is still the device clock. Reading timeExpireDate off the bolt11 removes any dependence on when the app recorded minting it — it does not make the check clock-independent, and an earlier draft of this PR wrongly claimed it did. Date.now() is the device wall clock, so a naive now >= timeExpireDate fails closed on skew: a handset running two minutes fast would mark every freshly minted 60-second invoice dead on arrival and lock that user out of sending entirely, where the backend (validating against server time) would have accepted the payment. So the guard carries a 120-second skew grace and a skew detector — a now that precedes the invoice's own timestamp proves the clock is behind and fails open. The incident's 18-minute-late retry is still caught with wide margin.
  • Undecodable invoices are allowed through. The backend still rejects a genuinely dead one, so a false negative costs nothing beyond today's behavior — while a false positive would block a perfectly good payment. Failing open is the right direction here, unlike the MAX case in fix(send): price LNURL sends instead of guessing a fee reserve #702.
  • paymentRequest is now surfaced on the payment detail. An LNURL detail's destination is the lightning address, not the bolt11, so the confirm screen previously had no way to inspect the invoice it was about to send.

Tests

__tests__/utils/invoice-expiry.spec.ts pins the real timestamps from the incident — attempt 1 must not be flagged (it wasn't an expiry failure), attempt 2 must be — plus the grace boundary, the full 60-second window, a fast clock, a past-dated invoice, willTransmitHeldInvoice across every wallet/type pair, and the fail-open paths.

The wiring is covered for real rather than by inspecting source text: the three existing __tests__/payment-details/*-payment-details.spec.ts now assert paymentRequest is surfaced (including that an LNURL detail gains it only via setInvoice), and __tests__/screens/send-confirmation.spec.tsx renders the actual confirm screen, presses Confirm, and asserts which copy appears and whether the send fired — including a BTC + LNURL case that must not be blocked. Reverting either behavioural fix turns two of those red.

Also in this PR (not ENG-555)

  • TopupDetails.allowanceExhausted i18n source-drift repair. The key already existed in app/i18n/en/index.ts and i18n-types.ts and was missing only from raw-i18n/source/en.json. It is top-up copy with nothing to do with ENG-555, flagged here so a later bisect of top-up copy knows where to look.
  • Locale propagation. allowanceExhausted and the new invoiceExpired are carried into all 23 files under raw-i18n/translations as the English string (the convention for untranslated keys here), which is what yarn check:translation-drift requires. Isolated in its own commit.
  • Firebase test mocks. __mocks__/@react-native-firebase/{analytics,crashlytics} exported only the legacy default factory, but the send flow uses the modular getAnalytics / getCrashlytics — so under jest every logged event threw and swallowed the call it wrapped. Added the named exports.

Follow-up (deliberately not here)

For LNURL sends the app could re-mint the invoice automatically instead of asking the user to go back. That needs the requestInvoice logic lifted out of send-bitcoin-details-screen.tsx, which is a refactor rather than a fix, so it's left separate.

Related

#702 (ENG-554) — the MAX fee-reserve bug found alongside this. They compound: MAX proposes an unsendable amount, the send fails, the user retries against a now-expired invoice, and both failures look identical on screen.

🤖 Generated with Claude Code

https://claude.ai/code/session_016MsAGwtS4sNodzWu2VMTKR

Flash IBEX receive invoices live 60 seconds — IBEX caps non-msat
accounts there, per IBEX_RECEIVE_MAX_EXPIRATION_SECONDS (ENG-427).
Verified on the invoice from the report: issued 16:39:42Z, expiring
16:40:42Z.

The confirmation screen holds whatever invoice was minted when the user
left the amount screen and resubmits it on every tap. In the reported
case the same paymentRequest was sent twice, 19 minutes apart — the
second attempt was ~18 minutes past expiry and could not have succeeded.
Both failures rendered as the same generic message, so the amount change
between them looked meaningful when it was irrelevant, and the
investigation chased the wrong cause.

Check the expiry before spending a round trip on a doomed send, and say
what actually happened. The expiry is read off the invoice rather than
timed locally, so clock skew or a backgrounded app cannot fool it, and
an undecodable invoice is allowed through — the backend still rejects a
genuinely dead one, so a false negative costs nothing while a false
positive would block a good payment.

Also surfaces paymentRequest on the payment detail: an LNURL detail's
"destination" is the lightning address, not the bolt11, so the confirm
screen previously had no way to inspect the invoice it was about to
send.

Tests: 661 pass, including the exact timestamps from the report and the
full 60-second window.

Follow-up worth doing: for LNURL sends the app could re-mint the invoice
automatically instead of asking the user to go back. That needs the
lnurl request logic lifted out of the details screen, so it is left
separate.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016MsAGwtS4sNodzWu2VMTKR
@linear

linear Bot commented Aug 20, 2026

Copy link
Copy Markdown

ENG-555

Dread and others added 8 commits August 20, 2026 11:18
Review found the guard was a no-op on most of the paths it appeared to
cover. Only createLnurlPaymentDetails exposed paymentRequest; the two
lightning factories did not, so a scanned or pasted invoice — also a
60-second Flash invoice — read undefined and sailed straight through to
the same generic error this fix exists to remove. Making the field
optional on BasePaymentDetail is what hid it: TypeScript was satisfied
and the guard looked universal while covering one case in three. All
three factories now return it.

A test now asserts that, by reading the factories' return objects. It
was verified to fail: removing paymentRequest from one factory reproduces
exactly the shipped bug and turns the suite red.

The network is now derived from the bolt11 prefix instead of hardcoded
to "mainnet". Hardcoding made the guard silently useless on signet and
regtest builds — the decoder throws on a prefix mismatch, the catch
swallows it, and nothing is ever checked. "lnbcrt" is tested before
"lnbc" since the shorter prefix would otherwise claim every regtest
invoice.

The decision itself moved into isHeldInvoiceExpired so it can be tested
without mounting the screen, and the tests drive it through the REAL
decoder on the REAL invoice from the incident — a stub would agree with
whatever the guard does and prove nothing. Both attempts are pinned: 38s
in must be allowed, 19 minutes late must be refused.

Fail-open behaviour is unchanged and now explicit: no invoice, an
unrecognised prefix, or a decode failure all allow the send. The backend
still rejects a dead invoice, so a false negative only restores today's
behaviour while a false positive blocks a good payment.

667 tests pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016MsAGwtS4sNodzWu2VMTKR
Two keys added to the en source were never propagated to the 23 files
under raw-i18n/translations, so `yarn check:translation-drift` — green at
this branch's base — now fails for every language:

  • TopupDetails.allowanceExhausted        (top-up copy, unrelated to
    ENG-555; it already existed in en/index.ts and i18n-types.ts and was
    missing only from the raw source, so this is a source-drift repair)
  • SendBitcoinConfirmationScreen.invoiceExpired  (ENG-555)

Both land as the English string, matching how every other untranslated
key in these files is carried (allowanceRemaining, allowanceHeld,
breezFeeText). Split out from the fix commit so a later bisect of top-up
copy lands here rather than inside an invoice-expiry change.
Review fixes for the ENG-555 expired-invoice guard.

Blocking

- The guard ran on every payment type, but BTC (Breez/Spark) LNURL and
  intraledger sends never transmit the held bolt11: useSendPayment routes
  them to payLnurlBreez, which re-resolves the address and mints a fresh
  invoice at send time. A BTC-wallet user paying a Flash lightning
  address who lingered on the confirm screen was refused a payment Breez
  would have completed — and `disabled={... || !!paymentError}` then
  locked the button. New `willTransmitHeldInvoice` gates the check;
  BTC + lightning still qualifies, since payLightningBreez is handed the
  detail's `destination`, which is the held bolt11.

- The refusal told every user to "go back and enter the amount again",
  which cannot work on the incident's own path. A scanned or pasted
  bolt11 is fixed: createNoAmountLightningPaymentDetails.setAmount
  returns the same invoice, and createAmountLightningPaymentDetails has
  canSetAmount: false, so there is no amount field at all. Only LNURL
  re-mints on the way forward. The copy now branches — the new string for
  PaymentType.Lnurl, the existing SendBitcoinDestinationScreen.
  expiredInvoice ("please generate a new invoice") otherwise.

- `nowSeconds >= timeExpireDate` compared against the device wall clock,
  so the guard failed CLOSED on skew: a handset two minutes fast marked
  every freshly minted 60-second invoice dead on arrival, permanently
  blocking a user the backend would have served. isInvoiceExpired now
  takes the bolt11 `timestamp` as well — a "now" preceding the issue time
  proves the clock is behind and fails open — and refuses only past
  timeExpireDate + CLOCK_SKEW_GRACE_SECONDS (120s), which still catches
  the report's 18-minute-late retry with margin. The comment claiming
  that reading the expiry off the invoice defeats clock skew was wrong
  and has been corrected: it removes dependence on a locally recorded
  mint time, not on the local clock.

- The only test covering the wiring was a regex over lightning.ts source
  text, which proved nothing about runtime. Deleted. Replaced with
  assertions in the three existing payment-details specs (including one
  that an LNURL detail gains paymentRequest only via setInvoice), a unit
  spec for willTransmitHeldInvoice, and three cases in
  __tests__/screens/send-confirmation.spec.tsx that render the real
  screen, press Confirm, and assert which copy appears and whether the
  send actually fired. Reverting either blocking fix turns two of them
  red.

Should-fix

- Named @galoymoney/client's `lightningInvoiceHasExpired` in
  invoice-expiry.ts and documented why the boundary and skew behaviour
  deliberately differ, so the two do not silently drift.
- Reverted the unrelated `!!paymentError` -> `Boolean(paymentError)`
  restyle.

Test infra

- __mocks__/@react-native-firebase/{analytics,crashlytics} exported only
  the legacy default; the send flow uses the modular getAnalytics /
  getCrashlytics, so every logged event threw and swallowed the call it
  wrapped. Added the named exports.
- Added the pay* functions to the breez-sdk mock and loaded the en
  dictionary in the screen spec (ContextForScreen mounts TypesafeI18n but
  nothing loads it, so LL.*() rendered as "").
Review fixes for the expired-invoice guard.

The absolute `now > expiry + 120s` comparison was the only signal, and it
compares the device clock against the issuer's, so it was wrong in both
directions. Under-shoot: on a 60-second Flash invoice it cannot fire until
the invoice is 180s old, so the ordinary confirm-screen pause the guard
exists to catch still spent the doomed round trip. Over-shoot: a handset
more than 180s fast read every freshly minted invoice as dead, blocking an
LNURL send that works today and pointing the user at a "fresh" invoice that
would read expired too.

The confirm screen now captures the device clock at mount and passes it in.
`nowSeconds - firstSeenSeconds` is a difference between two readings of the
same clock, so it is an elapsed duration no offset can inflate, and the
screen cannot mount before the invoice was minted — the elapsed term only
fires once the invoice's whole stated lifetime has genuinely passed. The
absolute comparison stays as a backstop for an invoice that aged before we
saw it, muted when the first sighting was already impossible.

Also:
- Log `payment_blocked_expired_invoice` when the guard refuses. Nothing is
  transmitted, so `payment_attempt` does not fire and no server trace exists
  either; without this a blocked send is as undiagnosable as the failure it
  replaced.
- Reword the LNURL remedy to "Go back and confirm again" and rename the key
  to `heldInvoiceExpired`. A fixed-amount LNURL (flashcard reload, fixed
  merchant QR) has `canSetAmount: false`, so "enter the amount again" sent
  that user hunting for a disabled field; going back and forward re-mints on
  its own. The old key was a transposition of
  SendBitcoinDestinationScreen.expiredInvoice, chosen two lines away.
- Revert an unrelated `!!` -> `Boolean()` restyle.

Tests: 90-second pause blocks, a 10-minutes-fast handset on a fresh invoice
does not, that same handset still blocks after a real pause, the analytics
event fires exactly once with the right params, and a fixed-amount LNURL
gets the followable copy.
Round-2 added a clause that muted the guard whenever the confirm screen's
FIRST reading already put the invoice past its lifetime, on the reasoning
that a stale-on-arrival invoice must mean a fast clock. The reported bug
is exactly that shape: after a failed send the Confirm button is disabled
for good, so the retry goes Back, changes the amount — setAmount rebuilds
the detail around the SAME bolt11 — and comes forward, remounting the
screen. The invoice really was 19 minutes dead on arrival.

Verified against the compiled module before and after: the reported
sequence returned false, i.e. the PR had stopped fixing its own bug.

The mute is gone. First sight is now recorded per INVOICE rather than per
screen mount, so it survives the remount and the elapsed measurement — the
one reading skew cannot inflate, since both ends come off the same clock —
sees the full lifetime pass. The screen registers on mount rather than on
tap, so a user who simply sits past the 60s window and taps once is caught
too, not just a retry.

The absolute comparison no longer overrides that elapsed reading. It
cannot tell a stale invoice from a fast handset, and letting it win blocked
a freshly minted invoice on a clock ten minutes fast — a good payment
refused, the one failure this guard must not introduce. It stays only as
the fallback for invoices carrying no usable issue time. The cost is
stated in the test: an invoice already stale when first seen is allowed
through to the backend, which rejects it.

Tests now drive the production entry point and seed first sight the way
the screen does, instead of passing a firstSeenSeconds argument the screen
never sends — the shape that let this survive a round. That parameter is
deleted, so the gap cannot reopen. All four behaviours are pinned: the
reported retry, a long single-tap pause, a fast clock on a fresh invoice,
and attempt one inside the window.

688 tests pass.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016MsAGwtS4sNodzWu2VMTKR
…e flow

Review fixes. The guard could never fire on a first sighting, so the most
common ENG-555 shape was still unhandled: scan another Flash user's 60s
invoice, spend two minutes on the amount screen choosing a wallet and
typing a number — nothing there re-mints a `lightning` detail — tap Next,
and confirm records first sight at its own mount. Elapsed is 0 by
construction, the elapsed-only branch returns false, and the corpse goes
to the backend as "Something went wrong".

First sight is now registered on send-bitcoin-details-screen, where a
scanned or pasted bolt11 actually arrives. The call is idempotent and
keyed by the invoice, so confirm's identical call becomes the no-op and
the elapsed reading spans the amount-screen pause. LNURL details have no
invoice until Next mints one, so their first sighting is still on the
confirm screen, which is correct.

The fail-open on an invoice never seen before is kept and now stated
plainly: that reading is indistinguishable from a fast handset clock, and
refusing there would make an LNURL send impossible on a device ten minutes
fast. The header docstring claimed the absolute backstop covered exactly
that case; it is structurally unreachable whenever a first-sight reading
exists, which is how the gap survived review. Rewritten to say what the
code does.

The headline unit test passed only on state leaked from its neighbour —
run alone it was red. The isHeldInvoiceExpired describe now resets module
state between cases and the retry test states its own premise, plus two
new cases pin the no-prior-sighting fail-open and the amount-screen pause.

The screen test's justification for always mounting on a live invoice was
false; replaced with the truth and a mount-already-dead case. New
regression test on the details screen fails without this change.

Also drops the unused useRef import and a truncated comment fragment left
by the previous commit.

692 tests pass; tsc, prettier and check-code clean.

Co-Authored-By: Claude Opus 5 <[email protected]>
… alive

Review fixes.

1. First sight was registered on the amount screen, one screen later than
the invoice is certified alive, so the destination-screen pause was still
a silent miss. `parsePaymentDestination` proves the bolt11 alive inside
`createLightningDestination`; from there the user still has to tap Next,
and on the paste/blur path the destination screen has already flipped to
Valid with ConfirmDestinationModal potentially sitting in front of an
unknown payee. A 60s Flash invoice arriving via a `lightning:` deep link,
plus a 90-second interruption, reached the details screen as a corpse:
the effect registered first sight on it, elapsed read 0, the elapsed
branch returned false, the absolute backstop stayed muted, and the send
went to the backend as ENG-555's "Something went wrong".

Registration now happens in `createLightningDestination`, which only runs
on `valid === true`, so partial keystrokes never register. It also
strengthens the design: `firstSeen` provably lands at a moment this
device's own clock said the invoice was alive, which is the property the
fail-open on an unseen invoice is paying for. The details-screen call is
kept as a backstop for anything reaching that screen another way.

2. The elapsed reading was the sole signal, and it is immune to a clock
with a constant OFFSET but not to one that MOVES between the two samples.
A handset five minutes slow (cold boot on a dead RTC, airplane mode off
after a flight) that scans a live 60s invoice, resyncs while the user
types an amount, then taps Confirm 25 seconds later reads 325s elapsed on
an invoice with 35 seconds of life left — refused, told to fetch a new
invoice, and Confirm disabled for good. A blocked good payment is the one
failure this module's docstring says it must not introduce.

The elapsed term now requires the absolute reading to corroborate. On any
stable clock the second term is implied (firstSeen >= timestamp + d
implies now > timeExpireDate + d), and a badly slow clock is already
muted by the `nowSeconds < timestamp` detector, so it only bites when the
clock jumped. It can only ever hold the guard back, never fire on its
own. Checked against all 14 elapsed-branch cases in the two suites; every
one still passes unchanged.

3. The eviction branch had zero coverage — nothing pushed the map past
MAX_TRACKED_INVOICES, so `keys().next()` picking the oldest insertion was
asserted nowhere. Swap it for the newest and the entry for the invoice in
flight is dropped, elapsed collapses to 0, the guard silently reverts to
fail-open, and the whole suite stays green. Three cases now pin it: the
first sighting wins over later ones, eviction takes the oldest and spares
the newest, and a repeat sighting is a read that does not reshuffle the
queue. MAX_TRACKED_INVOICES is exported so the test tracks the real cap.

Each new test was verified red against the unfixed code: dropping the
registration, dropping the corroboration, and evicting the newest instead
of the oldest each fail exactly the case written for it. Hoisting the
registration above the validity check fails too.

698 tests pass across 78 suites; tsc, eslint and prettier clean on every
changed file (the 5 pre-existing errors in send-bitcoin-details-screen
are unchanged in count and kind).

Co-Authored-By: Claude Opus 5 <[email protected]>
Six comments still said the primary signal was elapsed-since-mount. That
is the exact belief round 2 proved wrong — first sight is registered when
the destination is parsed, not when the confirm screen mounts, which is
what lets the reading survive the Back/change-amount/Forward remount in
the report. Left as-is, the registration calls in
payment-destination/lightning.ts and the details screen read as redundant
no-ops, and deleting either silently reopens ENG-555.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_016MsAGwtS4sNodzWu2VMTKR
@islandbitcoin
islandbitcoin merged commit 3f6e12d into main Aug 20, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants