taler-android

Android apps for GNU Taler (wallet, PoS, cashier)
Log | Files | Refs | README | LICENSE

suite.py (248754B)


      1 # This file is part of GNU Taler
      2 # (C) 2026 Taler Systems S.A.
      3 #
      4 # GNU Taler is free software; you can redistribute it and/or modify it under the
      5 # terms of the GNU General Public License as published by the Free Software
      6 # Foundation; either version 3, or (at your option) any later version.
      7 #
      8 # GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
      9 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     10 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
     11 #
     12 # You should have received a copy of the GNU General Public License along with
     13 # GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     14 """Feature scenarios, run as a suite.
     15 
     16 Each scenario walks one feature of the wallet deliberately, rather than at
     17 random: the transaction list and its per-transaction actions, exchange
     18 management, every settings row, the scan screen's manual entry, deposits and
     19 peer payments.  Random exploration finds the sequences nobody thought of;
     20 these make sure the obvious ones are covered at all.
     21 
     22 A scenario failing because a label moved is *not* a finding — it is recorded
     23 as a driver error so the two never get confused.  Real findings come from the
     24 oracles in oracles.py.
     25 
     26     python3 suite.py                 # every scenario
     27     python3 suite.py history exchange_add_remove
     28     python3 suite.py --list
     29 """
     30 
     31 from __future__ import annotations
     32 
     33 import json
     34 import os
     35 import re
     36 import sys
     37 import time
     38 from pathlib import Path
     39 import traceback
     40 from dataclasses import dataclass, field
     41 from typing import Callable, Optional
     42 
     43 sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "corpus"))
     44 
     45 import oracles  # noqa: E402
     46 import scenarios as flows  # noqa: E402
     47 import uris as corpus  # noqa: E402
     48 from cli import CliWallet  # noqa: E402
     49 from twister import FAULTS, Twister, TwisterUnavailable  # noqa: E402
     50 from device import PKG, Device, Screen  # noqa: E402
     51 from episode import Episode  # noqa: E402
     52 import stack as stack_mod  # noqa: E402
     53 from stack import Bank, Env, Merchant  # noqa: E402
     54 
     55 WORKER = int(os.environ.get("SIM_WORKER", "0"))
     56 SERIAL = os.environ.get("SIM_SERIAL", f"emulator-{5554 + 2 * WORKER}")
     57 OUT = Path("/opt/taler-sim/run/out")
     58 # Where the JaCoCo dumps land.  Settable so that a run against a *different*
     59 # build -- a patched APK, say -- can keep its dumps out of the campaign's
     60 # report: JaCoCo keys classes by a hash of their bytecode, so dumps from two
     61 # builds cannot be merged.
     62 COVERAGE = Path(os.environ.get("SIM_COVERAGE_DIR",
     63                                "/opt/taler-sim/run/coverage"))
     64 LOCAL_EXCHANGE = "http://localhost:8081/"
     65 # The second exchange, if backend/exchange2.sh has been started beside the
     66 # stack.  Scenarios that need a choice check for it rather than assume it.
     67 SECOND_EXCHANGE = "http://localhost:8091/"
     68 # Services deployed beside the stack, with their own databases: the Taler
     69 # mailbox (whose URL the wallet lets you type in) and the Taler directory
     70 # (whose URL the app hard-codes, so only wallet-core can be pointed at it).
     71 LOCAL_MAILBOX = "http://localhost:11000/"
     72 LOCAL_TALDIR = "http://localhost:11001/"
     73 
     74 
     75 class Ctx:
     76     """What a scenario gets to work with."""
     77 
     78     def __init__(self, ep: Episode, env: Env):
     79         self.ep = ep
     80         self.dev = ep.dev
     81         self.app = ep.app
     82         self.env = env
     83         self.bank = Bank(env.bank)
     84         self.merchant = Merchant(env.merchant)
     85         self.cli = CliWallet()
     86         self.notes: list[str] = []
     87 
     88     # Tolerant helpers: a scenario says what it wants to touch, and missing
     89     # optional elements do not abort the walk.
     90 
     91     def tap(self, pattern: str, timeout: int = 12) -> bool:
     92         try:
     93             self._tap_watching(pattern, timeout)
     94             return True
     95         except TimeoutError:
     96             return False
     97 
     98     def must_tap(self, pattern: str, timeout: int = 30) -> None:
     99         self._tap_watching(pattern, timeout)
    100 
    101     def accept_tos(self) -> bool:
    102         """Get past the exchange's terms of service, if it has any."""
    103         accepted = flows.accept_tos(self.app)
    104         if accepted:
    105             self.note("accepted the exchange's terms of service")
    106             self.check()
    107         return accepted
    108 
    109     def tap_exact(self, pattern: str, timeout: int = 12) -> bool:
    110         """Tap the matching node's own centre, with no hunt for an ancestor.
    111 
    112         `tap` and `tap_button` look for a clickable ancestor or neighbour when
    113         the matching node is not itself clickable, which is right for a label
    114         inside a button and wrong in three places this campaign has now hit:
    115 
    116         * a document picker's rows, where the hunt lands somewhere that
    117           dismisses the picker without selecting (`pick_file_in_picker`);
    118         * a Compose `AlertDialog`'s text buttons, where it dismissed the
    119           mailbox address dialog instead of pressing Copy;
    120         * a dropdown item, whose clickable ancestor is the menu rather than
    121           the item.
    122 
    123         In all three the node's own centre is inside the real touch target, so
    124         tapping it directly is both simpler and correct.  Use this when the
    125         thing being tapped is a row, a dialog button or a menu item.
    126         """
    127         deadline = time.time() + timeout
    128         rx = re.compile(pattern, re.I)
    129         while time.time() < deadline:
    130             screen = self.dev.dump()
    131             node = next((n for n in screen.labelled()
    132                          if rx.search(n.label.strip())), None)
    133             if node is not None:
    134                 self.dev.tap(*node.center)
    135                 return True
    136             time.sleep(1)
    137         return False
    138 
    139     def tap_button(self, pattern: str, timeout: int = 12) -> bool:
    140         """Tap a *button* whose label is used elsewhere on the same screen.
    141 
    142         Several screens give the title and the submit button the same string --
    143         "Add account" is the app bar title, the list screen's add icon and the
    144         form's submit button -- and `find` returns the first match, which is
    145         the title.  A title is not clickable, so its tap goes nowhere (or, via
    146         the neighbour search, to the back arrow).  This picks the lowest
    147         matching node that is clickable or sits inside something clickable.
    148         """
    149         deadline = time.time() + timeout
    150         rx = re.compile(pattern, re.I)
    151         while time.time() < deadline:
    152             screen = self.dev.dump()
    153             matches = [n for n in screen.labelled() if rx.search(n.label)]
    154             targets = []
    155             for n in matches:
    156                 target = screen.tap_target(n)
    157                 if not (target.clickable and target.enabled):
    158                     continue
    159                 # tap_target also looks at clickable *neighbours*, which on
    160                 # this screen means a tab beside the title: a disabled submit
    161                 # button would otherwise be "tapped" by switching tabs.  Only
    162                 # a target that is the label itself, or contains it, counts.
    163                 x, y = n.center
    164                 x1, y1, x2, y2 = target.bounds
    165                 if target is n or (x1 <= x <= x2 and y1 <= y <= y2):
    166                     targets.append(target)
    167             if targets:
    168                 lowest = max(targets, key=lambda t: t.center[1])
    169                 before = screen.signature()
    170                 self.dev.tap(*lowest.center)
    171                 time.sleep(1.2)
    172                 after = self.dev.dump()
    173                 fresh = self.ep.session.add(oracles.silent_failure(
    174                     self.dev, pattern, before, after.signature()))
    175                 for finding in fresh:
    176                     self.ep._capture(finding, after, None)
    177                 return True
    178             time.sleep(1)
    179         return False
    180 
    181     def _tap_watching(self, pattern: str, timeout: int) -> None:
    182         """Tap, and notice when the tap achieves nothing but an error."""
    183         before = self.dev.dump()
    184         screen = self.dev.tap_text(pattern, timeout=timeout)
    185         time.sleep(1.2)
    186         after = self.dev.dump()
    187         fresh = self.ep.session.add(oracles.silent_failure(
    188             self.dev, pattern, before.signature(), after.signature()))
    189         for finding in fresh:
    190             self.ep._capture(finding, after, None)
    191 
    192     def see(self, pattern: str, timeout: int = 15) -> Optional[Screen]:
    193         try:
    194             return self.dev.wait_for(pattern, timeout=timeout)
    195         except TimeoutError:
    196             return None
    197 
    198     def set_amount(self, chip: str = "€5.00", digits: str = "500") -> bool:
    199         """Choose an amount, by quick-amount chip if the screen offers one.
    200 
    201         The amount fields do not always take injected text — focus does not
    202         always follow the tap — but every amount screen also offers preset
    203         chips, which is what a user would reach for anyway.
    204         """
    205         screen = self.dev.dump()
    206         preset = screen.find(rf"(?i)^{re.escape(chip)}$")
    207         if preset is not None:
    208             self.dev.tap_node(preset, screen)
    209             time.sleep(1.5)
    210             if self.dev.dump().find(rf"(?i){re.escape(chip)}"):
    211                 return True
    212         return self.fill(digits)
    213 
    214     def require(self, pattern: str, timeout: int = 30) -> Screen:
    215         """Insist on reaching a screen.
    216 
    217         Without this a scenario whose entry point silently fails to open still
    218         reports "ok" having exercised nothing, which is worse than a failure:
    219         it hides a gap behind a green row.
    220         """
    221         screen = self.see(pattern, timeout=timeout)
    222         if screen is None:
    223             raise RuntimeError(
    224                 f"expected a screen matching {pattern!r}; "
    225                 f"got {self.dev.dump().texts()}"
    226             )
    227         return screen
    228 
    229     def note(self, text: str) -> None:
    230         self.notes.append(text)
    231 
    232     def uri_from_logcat(self, kind: str, timeout: int = 30) -> str:
    233         """Pull a URI the wallet just generated out of wallet-core's log.
    234 
    235         The Send/Request screens show the URI as a QR code and in a copy
    236         button, neither of which can be read from the view hierarchy, but
    237         wallet-core logs its own response.
    238         """
    239         import re as _re
    240         pattern = _re.compile(r"taler(?:\+http)?://" + kind + r"/[A-Za-z0-9:._/?=&%-]+")
    241         deadline = time.time() + timeout
    242         while time.time() < deadline:
    243             for match in pattern.finditer(self.dev.logcat()):
    244                 return match.group(0).rstrip('\\"\',.)')
    245             time.sleep(2)
    246         raise RuntimeError(f"no taler://{kind}/ URI in the log")
    247 
    248     def fill(self, value: str, which: int = 0, clear: bool = False) -> bool:
    249         """Type into the n-th editable field on the current screen.
    250 
    251         Amount fields append digits from the right, as a cash register does:
    252         typing "5" yields 0.05 and "500" yields 5.00.  Scenarios therefore pass
    253         the digit sequence they want, not a decimal string.
    254 
    255         `clear` empties a pre-filled field first.  Deleting backwards from the
    256         tap position leaves whatever was to the right of it -- which is how
    257         "https://mailbox.gnunet.org" became
    258         "http://localhost:11000unet.org" -- so the cursor goes to the end
    259         first.
    260         """
    261         screen = self.dev.dump()
    262         fields = screen.editable()
    263         if len(fields) <= which:
    264             return False
    265         field = fields[which]
    266         if clear:
    267             # Tapping the node's centre puts the cursor in the middle of the
    268             # text, and KEYCODE_MOVE_END does not move it in a Compose field,
    269             # so deleting backwards left the tail behind: tap just inside the
    270             # right-hand edge instead, where the cursor lands after the last
    271             # character.
    272             x1, y1, x2, y2 = field.bounds
    273             self.dev.tap(max(x1 + 1, x2 - 12), (y1 + y2) // 2)
    274             time.sleep(0.5)
    275             self.dev.shell("input keyevent " + " ".join(["KEYCODE_DEL"] * 80),
    276                            check=False)
    277             time.sleep(0.5)
    278         else:
    279             self.dev.tap_node(field, screen)
    280             time.sleep(0.5)
    281         self.dev.type_text(value)
    282         time.sleep(0.5)
    283         return True
    284 
    285     def check(self) -> None:
    286         """Run the oracles against the current screen."""
    287         self.ep.observe()
    288 
    289     def back_to_home(self) -> None:
    290         self.app.home()
    291 
    292 
    293 @dataclass
    294 class Scenario:
    295     name: str
    296     setup: str          # fresh | funded | paid | keep
    297     fn: Callable[[Ctx], None]
    298     about: str = ""
    299     # Finding kinds this scenario provokes on purpose: corrupting the database
    300     # is supposed to produce an init error, and pointing the wallet at a dead
    301     # host is supposed to produce connection failures.  Reporting those as
    302     # defects every round would bury the real ones.
    303     expects: tuple[str, ...] = ()
    304 
    305 
    306 REGISTRY: dict[str, Scenario] = {}
    307 
    308 
    309 def scenario(name: str, setup: str = "keep", about: str = "",
    310              expects: tuple[str, ...] = ()) -> Callable:
    311     def register(fn: Callable[[Ctx], None]) -> Callable[[Ctx], None]:
    312         REGISTRY[name] = Scenario(name=name, setup=setup, fn=fn,
    313                                   about=about or fn.__doc__ or "", expects=expects)
    314         return fn
    315     return register
    316 
    317 
    318 # --------------------------------------------------------------- navigation ---
    319 
    320 # Section headers and chips that sit below "Recent transactions" but are not
    321 # transactions themselves.
    322 BELOW_BUT_NOT_A_TRANSACTION = (
    323     "all", "discounts", "passes", "donation statements", "other assets",
    324     "settings", "internal event log", "scan qr code", "contacts", "pending",
    325     "where to pay", "shopping",
    326     # The dedicated transactions screen puts the balance card between its app
    327     # bar and the list, and that card carries an unsigned amount and a
    328     # relative time -- enough to be taken for a transaction, whose row then
    329     # swallowed every long press aimed at the first "transaction".
    330     "balance",
    331 )
    332 # A transaction row always carries a relative time and a signed amount; either
    333 # is enough to tell it apart from a header or a chip.
    334 TIME_LABEL = re.compile(r"(?i)\b(ago|yesterday|today)\b|\d{1,2}:\d\d|\d{4}")
    335 AMOUNT_LABEL = re.compile(r"^[+\-\u2212]?\s*\d+[.,]\d\d$")
    336 # Only a transaction's amount carries a sign; a balance is printed bare.
    337 SIGNED_AMOUNT_LABEL = re.compile(r"^[+\-\u2212]\s*\d+[.,]\d\d$")
    338 
    339 
    340 def open_transactions(c: Ctx) -> Screen:
    341     """The main screen lists the recent transactions itself.
    342 
    343     There is no separate list screen: the balance pager shows a "Recent
    344     transactions" header with the transactions under it, and tapping one opens
    345     its detail screen.
    346     """
    347     c.back_to_home()
    348     screen = c.dev.dump()
    349     if screen.find(r"(?i)^Recent transactions$") is None:
    350         try:
    351             screen = c.app.scroll_to_text(r"(?i)^Recent transactions$", max_scrolls=4)
    352         except TimeoutError:
    353             c.note("no transaction section on the main screen")
    354     return screen
    355 
    356 
    357 def open_exchange_list(c: Ctx) -> None:
    358     """Settings -> Payment services, the exchange list."""
    359     c.app.open_settings()
    360     c.app.scroll_to_text(r"(?i)^Payment services$")
    361     c.must_tap(r"(?i)^Payment services$")
    362     c.see(r"(?i)Add payment service|Currency:|No payment services")
    363 
    364 
    365 def exchange_menu(c: Ctx, which: str = "localhost") -> bool:
    366     """Open the per-exchange menu, whose label embeds the exchange URL."""
    367     return c.tap(rf"(?i)^Menu: .*{which}", timeout=25)
    368 
    369 
    370 def transaction_rows(screen: Screen,
    371                      header: str = r"(?i)^Recent transactions$",
    372                      signed_only: bool = False) -> list:
    373     """One tap target per transaction listed under the header.
    374 
    375     Nodes are grouped into horizontal bands, because a row is several nodes
    376     (time, title, amount); a band counts as a transaction when something in it
    377     looks like a time or a signed amount, which keeps the filter chips and the
    378     "Discounts"/"Passes" sections out.
    379 
    380     The default header is the main screen's section title.  The dedicated
    381     transactions screen behind the "All" chip has no such header -- its rows
    382     sit under the app bar -- so a caller there passes the screen's own title
    383     instead, and the banding works the same way.
    384     """
    385     header_node = screen.find(header)
    386     if header_node is None:
    387         return []
    388     top = header_node.center[1]
    389     bands: dict[int, list] = {}
    390     for node in screen.tappable():
    391         label = node.label.strip()
    392         if not label or node.center[1] <= top:
    393             continue
    394         bands.setdefault(node.center[1] // 110, []).append(node)
    395     rows = []
    396     for band in sorted(bands):
    397         nodes = bands[band]
    398         labels = [n.label.strip() for n in nodes]
    399         if any(l.lower() in BELOW_BUT_NOT_A_TRANSACTION for l in labels):
    400             continue
    401         # With signed_only, a band needs an amount carrying a sign.  The
    402         # dedicated transactions screen shows a balance card above the list,
    403         # and its parts -- the currency, the exchange URL, the bare amount --
    404         # band into something that looks exactly like a transaction; the first
    405         # "row" there was the exchange URL, which swallowed every long press.
    406         amount = SIGNED_AMOUNT_LABEL if signed_only else AMOUNT_LABEL
    407         if signed_only:
    408             if not any(amount.match(l) for l in labels):
    409                 continue
    410         elif not any(TIME_LABEL.search(l) or amount.match(l) for l in labels):
    411             continue
    412         # Prefer the title over the time or the amount as the tap target.
    413         target = next((n for n in nodes
    414                        if not TIME_LABEL.search(n.label.strip())
    415                        and not AMOUNT_LABEL.match(n.label.strip())
    416                        and "://" not in n.label), nodes[0])
    417         rows.append(target)
    418     return rows
    419 
    420 
    421 # ---------------------------------------------------------------- scenarios ---
    422 
    423 @scenario("history", setup="paid", about="transaction list, details, JSON view, filters")
    424 def s_history(c: Ctx) -> None:
    425     screen = open_transactions(c)
    426     c.note(f"main screen: {screen.texts()[:14]}")
    427     rows = transaction_rows(screen)
    428     c.note(f"{len(rows)} transaction rows: {[n.label[:28] for n in rows]}")
    429     opened = 0
    430     for index in range(min(len(rows), 4)):
    431         screen = open_transactions(c)
    432         rows = transaction_rows(screen)
    433         if index >= len(rows):
    434             break
    435         c.dev.tap_node(rows[index], screen)
    436         time.sleep(2)
    437         detail = c.dev.dump()
    438         if detail.find(r"(?i)^Show JSON$|completed successfully|^Delete$|^Transaction$"):
    439             opened += 1
    440             c.note(f"detail {index}: {detail.texts()[:10]}")
    441             c.check()
    442             # The raw JSON view is dev-mode only and renders the whole
    443             # transaction record.
    444             if c.tap(r"(?i)^Show JSON$", timeout=10):
    445                 c.check()
    446                 c.dev.back()
    447                 time.sleep(1)
    448         else:
    449             c.note(f"row {index} did not open a detail screen: {detail.texts()[:8]}")
    450         c.dev.back()
    451         time.sleep(1)
    452     c.note(f"opened {opened} transaction detail screens")
    453     if opened == 0 and rows:
    454         raise RuntimeError("transaction rows present but none opened a detail screen")
    455     c.check()
    456 
    457 
    458 @scenario("history_delete", setup="paid", about="delete a finished transaction")
    459 def s_history_delete(c: Ctx) -> None:
    460     screen = open_transactions(c)
    461     rows = transaction_rows(screen)
    462     before = len(rows)
    463     if not rows:
    464         raise RuntimeError(f"no transaction rows to delete; screen: {screen.texts()}")
    465     c.dev.tap_node(rows[0], screen)
    466     time.sleep(1.5)
    467     c.must_tap(r"(?i)^Delete$")
    468     # A confirmation dialog guards the deletion.
    469     if c.see(r"(?i)Delete transaction|Are you sure"):
    470         c.tap(r"(?i)^Delete$|^OK$|^Yes$")
    471     time.sleep(2)
    472     after = len(transaction_rows(open_transactions(c)))
    473     c.note(f"transaction rows before={before} after={after}")
    474     if after >= before:
    475         c.note("WARNING: the row count did not drop after deleting")
    476     c.check()
    477 
    478 
    479 @scenario("withdraw_suspend_resume", setup="fresh",
    480           about="suspend a pending withdrawal, then resume it")
    481 def s_withdraw_suspend_resume(c: Ctx) -> None:
    482     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
    483     c.app.handle_uri(op["taler_withdraw_uri"])
    484     c.accept_tos()
    485     c.must_tap(r"(?i)confirm withdrawal", timeout=60)
    486     # The transaction now waits for the bank; its detail screen offers the
    487     # lifecycle actions.
    488     c.see(r"(?i)Waiting for authorization|Authorize in bank", timeout=60)
    489     c.must_tap(r"(?i)^Suspend$")
    490     if c.see(r"(?i)Are you sure|Suspend"):
    491         c.tap(r"(?i)^Suspend$|^OK$|^Yes$", timeout=6)
    492     time.sleep(2)
    493     detail = c.dev.dump()
    494     c.note("suspended, on its detail screen: " + str(detail.texts()[:12]))
    495     c.check()
    496     # What the *list* says about it: the detail screen says "This transaction
    497     # is suspended", and the row is what a user scanning their history sees.
    498     row_texts = []
    499     c.back_to_home()
    500     listed = c.dev.dump()
    501     rows = transaction_rows(listed)
    502     if rows:
    503         band = rows[0].bounds
    504         row_texts = [n.label for n in listed.labelled()
    505                      if abs(n.bounds[1] - band[1]) < 120]
    506     c.note(f"its row in the list: {row_texts}")
    507     if row_texts and not any("suspend" in t.lower() for t in row_texts):
    508         c.note("WARNING: nothing on the row says the transaction is suspended")
    509     c.check()
    510     rows = transaction_rows(c.dev.dump())
    511     if rows:
    512         c.dev.tap_node(rows[0])
    513         time.sleep(2.5)
    514     c.must_tap(r"(?i)^Resume$", timeout=30)
    515     time.sleep(2)
    516     c.note("resumed; screen: " + str(c.dev.dump().texts()[:8]))
    517     c.check()
    518 
    519 
    520 @scenario("withdraw_suspend_abort", setup="fresh",
    521           about="suspend a pending withdrawal, then abort it")
    522 def s_withdraw_suspend_abort(c: Ctx) -> None:
    523     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
    524     c.app.handle_uri(op["taler_withdraw_uri"])
    525     c.accept_tos()
    526     c.must_tap(r"(?i)confirm withdrawal", timeout=60)
    527     c.see(r"(?i)Waiting for authorization|Authorize in bank", timeout=60)
    528     c.must_tap(r"(?i)^Suspend$")
    529     time.sleep(2)
    530     c.must_tap(r"(?i)^Abort$", timeout=30)
    531     if c.see(r"(?i)Abort transaction|Are you sure"):
    532         c.tap(r"(?i)^Abort$|^OK$|^Yes$")
    533     time.sleep(3)
    534     c.note("after abort: " + str(c.dev.dump().texts()[:10]))
    535     c.check()
    536 
    537 
    538 @scenario("withdraw_abort", setup="fresh", about="abort a withdrawal before the bank confirms")
    539 def s_withdraw_abort(c: Ctx) -> None:
    540     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
    541     c.app.handle_uri(op["taler_withdraw_uri"])
    542     c.accept_tos()
    543     c.must_tap(r"(?i)confirm withdrawal", timeout=60)
    544     c.see(r"(?i)Waiting for authorization|Authorize in bank", timeout=60)
    545     c.must_tap(r"(?i)^Abort$")
    546     if c.see(r"(?i)Abort transaction|Are you sure"):
    547         c.tap(r"(?i)^Abort$|^OK$|^Yes$")
    548     time.sleep(3)
    549     status = c.bank.withdrawal_status(op["withdrawal_id"])
    550     c.note(f"bank-side status after abort: {status.get('status')}")
    551     # What the aborted transaction says about itself: nothing was withdrawn, so
    552     # "Fee -<the whole amount>" would be a misstatement.  Aborting navigates
    553     # back to the list, so the detail screen has to be opened again.
    554     aborted = c.dev.dump()
    555     if aborted.find(r"(?i)was aborted|has failed") is None:
    556         open_transactions(c)
    557         rows = transaction_rows(c.dev.dump())
    558         if rows:
    559             c.dev.tap_node(rows[0])
    560             time.sleep(2.5)
    561         aborted = c.dev.dump()
    562     c.note("aborted withdrawal: " + str(aborted.texts()[:14]))
    563     labels = aborted.texts()
    564     if "Fee" in labels:
    565         fee_node = aborted.find(r"(?i)^Fee$")
    566         amounts = [t for t in labels if re.match(r"^[-−]?[€$]?\d", t)]
    567         c.note(f"amounts beside Fee: {amounts[:6]}")
    568         if any(t.lstrip("-−").lstrip("€$") == "5.00" for t in amounts):
    569             c.note("WARNING: the whole chosen amount is shown as a fee")
    570     c.check()
    571 
    572 
    573 @scenario("withdraw_abandon", setup="fresh", about="abandon (fail) a pending withdrawal")
    574 def s_withdraw_abandon(c: Ctx) -> None:
    575     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
    576     c.app.handle_uri(op["taler_withdraw_uri"])
    577     c.accept_tos()
    578     c.must_tap(r"(?i)confirm withdrawal", timeout=60)
    579     c.see(r"(?i)Waiting for authorization|Authorize in bank", timeout=60)
    580     if not c.tap(r"(?i)^Abandon$", timeout=20):
    581         # Abandon is only offered in some states; suspend first and look again.
    582         c.tap(r"(?i)^Suspend$")
    583         if not c.tap(r"(?i)^Abandon$", timeout=20):
    584             c.note("Abandon not offered for a withdrawal waiting on the bank")
    585             return
    586     if c.see(r"(?i)Abandon transaction|Are you sure"):
    587         c.tap(r"(?i)^Abandon$|^OK$|^Yes$")
    588     time.sleep(3)
    589     c.check()
    590 
    591 
    592 # "funded" rather than "fresh": the exchange menu only exists once the wallet
    593 # knows the local exchange, which the first withdrawal is what teaches it.
    594 @scenario("withdraw_manual", setup="funded",
    595           about="manual withdrawal from the exchange menu: wire instructions and QR")
    596 def s_withdraw_manual(c: Ctx) -> None:
    597     open_exchange_list(c)
    598     if not exchange_menu(c):
    599         raise RuntimeError(f"no exchange menu; screen: {c.dev.dump().texts()}")
    600     if not c.tap(r"(?i)^Withdraw$"):
    601         c.note("no manual withdraw entry in the exchange menu")
    602         return
    603     screen = c.see(r"(?i)Withdraw|amount|Confirm", timeout=30)
    604     fields = screen.editable() if screen else []
    605     if fields:
    606         c.dev.tap_node(fields[0], screen)
    607         c.dev.type_text("5")
    608     c.accept_tos()
    609     c.tap(r"(?i)^Withdraw$|Confirm withdrawal", timeout=20)
    610     # Wire transfer instructions, with the QR variants below them.
    611     if c.see(r"(?i)Wire transfer instructions|Subject|IBAN|Recipient", timeout=40):
    612         c.note("reached manual withdrawal instructions")
    613         c.app.scroll_to_text(r"(?i)Wire transfer QR codes|Open in banking app", max_scrolls=5)
    614     c.check()
    615 
    616 
    617 @scenario("payment_abort", setup="funded", about="decline a payment at the prompt")
    618 def s_payment_abort(c: Ctx) -> None:
    619     order = c.merchant.create_order("EUR:1", summary="Order the wallet will decline")
    620     c.app.handle_uri(order["pay_uri"])
    621     c.see(r"(?i)Review order|Total:|^Pay", timeout=60)
    622     c.must_tap(r"(?i)^Cancel$")
    623     time.sleep(2)
    624     status = c.merchant.order_status(order["order_id"], order["token"])
    625     c.note(f"order status after cancel: {status.get('order_status')}")
    626     c.check()
    627 
    628 
    629 @scenario("payment_insufficient", setup="funded",
    630           about="an order larger than the balance, and what the Pay button does")
    631 def s_payment_insufficient(c: Ctx) -> None:
    632     order = c.merchant.create_order("EUR:99", summary="More than the wallet holds")
    633     c.app.handle_uri(order["pay_uri"])
    634     screen = c.require(r"(?i)insufficient|not enough|balance|Review order", timeout=40)
    635     c.note("screen: " + str(screen.texts()[:12]))
    636     pay = screen.find(r"(?i)^Pay ")
    637     if pay is not None:
    638         button = screen.tap_target(pay)
    639         c.note(f"Pay button present with an insufficient balance: "
    640                f"label={pay.label!r} enabled={button.enabled} "
    641                f"clickable={button.clickable}")
    642         # Offering it is only a problem if it can actually be pressed.
    643         if button.enabled and button.clickable:
    644             c.dev.tap_node(pay, screen)
    645             time.sleep(4)
    646             after = c.dev.dump()
    647             c.note("after pressing Pay anyway: " + str(after.texts()[:12]))
    648             status = c.merchant.order_status(order["order_id"], order["token"])
    649             c.note(f"merchant says: {status.get('order_status')}")
    650             c.check()
    651     else:
    652         c.note("no Pay button offered, which is the expected behaviour")
    653     c.check()
    654     c.ep.check_database()
    655 
    656 
    657 @scenario("payment_twice", setup="funded", about="pay the same order twice")
    658 def s_payment_twice(c: Ctx) -> None:
    659     order = flows.pay(c.app, c.merchant, "EUR:1", summary="Paid once already")
    660     c.app.home()
    661     c.app.handle_uri(order["pay_uri"])
    662     c.see(r"(?i)already paid|paid|Error|Review order", timeout=40)
    663     c.note("second attempt: " + str(c.dev.dump().texts()[:10]))
    664     c.check()
    665 
    666 
    667 @scenario("refund", setup="funded", about="take a refund for a paid order")
    668 def s_refund(c: Ctx) -> None:
    669     order = flows.pay(c.app, c.merchant, "EUR:2", summary="Order to be refunded")
    670     c.app.home()
    671     res = c.merchant.refund(order["order_id"], "EUR:1")
    672     uri = res.get("taler_refund_uri")
    673     if not uri:
    674         raise RuntimeError(f"merchant returned no refund uri: {res}")
    675     c.app.handle_uri(uri)
    676     time.sleep(3)
    677     c.note("after refund uri: " + str(c.dev.dump().texts()[:10]))
    678     open_transactions(c)
    679     c.check()
    680 
    681 
    682 @scenario("exchange_add_remove", setup="fresh", about="add an exchange by URL, then delete it")
    683 def s_exchange_add_remove(c: Ctx) -> None:
    684     open_exchange_list(c)
    685     c.must_tap(r"(?i)^Add payment service$")
    686     screen = c.require(r"(?i)Enter address of payment service|address", timeout=30)
    687     fields = screen.editable() if screen else []
    688     if not fields:
    689         raise RuntimeError(f"no URL field on the add screen: {screen.texts() if screen else None}")
    690     c.dev.tap_node(fields[0], screen)
    691     c.dev.type_text(LOCAL_EXCHANGE)
    692     c.tap(r"(?i)^Add$|^OK$|^Continue$|^Next$")
    693     time.sleep(4)
    694     c.check()
    695     # Now remove it again.
    696     open_exchange_list(c)
    697     if exchange_menu(c):
    698         if c.tap(r"(?i)^Delete payment service$"):
    699             if c.see(r"(?i)Force deletion|Are you sure|Delete"):
    700                 c.tap(r"(?i)^Delete$|^OK$|^Yes$", timeout=8)
    701             time.sleep(2)
    702             c.note("deleted the local exchange")
    703     c.check()
    704 
    705 
    706 @scenario("exchange_tos", setup="fresh", about="view, reject and re-accept terms of service")
    707 def s_exchange_tos(c: Ctx) -> None:
    708     # Contact the exchange first so there are terms to look at.
    709     flows.withdraw(c.app, c.bank, "EUR:5")
    710     open_exchange_list(c)
    711     if not exchange_menu(c):
    712         raise RuntimeError(f"no exchange menu; screen: {c.dev.dump().texts()}")
    713     if c.tap(r"(?i)^Review terms of service$"):
    714         shown = c.see(r"(?i)Terms of Service|Accept|terms", timeout=30)
    715         c.check()
    716         # The language selector only exists when the exchange offers more than
    717         # one language, which is why backend/stack.sh renders the terms in
    718         # English *and* German (exchange-tos-tops-v0 ships both).
    719         if shown is not None and shown.find(r"(?i)^Language$") is not None:
    720             before = [x for x in shown.texts() if len(x) > 40][:1]
    721             c.tap(r"(?i)^Language$", timeout=10)
    722             time.sleep(2)
    723             menu = c.dev.dump()
    724             # The menu items are text nodes whose clickable ancestor is the
    725             # row, so they do not appear in tappable() -- looking there found
    726             # nothing and read as "the exchange offers one language".
    727             known = ("English", "German", "Deutsch", "French", "Français")
    728             offered = [n for n in menu.labelled() if n.label.strip() in known]
    729             c.note(f"languages offered: {[n.label.strip() for n in offered]}")
    730             other = next((n for n in offered
    731                           if n.label.strip() != "English"), None)
    732             if other is not None and (c.dev.tap(*other.center) or True):
    733                 time.sleep(3)
    734                 after = c.dev.dump()
    735                 body = [x for x in after.texts() if len(x) > 40][:1]
    736                 c.note(f"after picking {other.label.strip()!r}: {str(body)[:160]}")
    737                 if before and body and before == body:
    738                     c.note("the terms text did not change with the language")
    739             c.check()
    740         else:
    741             c.note("no language selector on the terms screen: "
    742                    + str(shown.texts()[:10] if shown else None))
    743         c.dev.back()
    744     open_exchange_list(c)
    745     exchange_menu(c)
    746     if c.tap(r"(?i)^Reject terms of service$"):
    747         time.sleep(2)
    748         c.note("rejected the terms of service")
    749         c.check()
    750     open_exchange_list(c)
    751     exchange_menu(c)
    752     if c.tap(r"(?i)^Accept Terms of Service$|^Review terms of service$"):
    753         c.tap(r"(?i)^Accept$|I accept|^Confirm$", timeout=20)
    754     c.check()
    755 
    756 
    757 @scenario("exchange_reload_global", setup="funded",
    758           about="reload exchange info and toggle global-currency treatment")
    759 def s_exchange_reload_global(c: Ctx) -> None:
    760     open_exchange_list(c)
    761     if not exchange_menu(c):
    762         raise RuntimeError(f"no exchange menu; screen: {c.dev.dump().texts()}")
    763     menu = c.dev.dump()
    764     c.note("exchange menu: " + str(menu.texts()[:14]))
    765     if c.tap(r"(?i)^Reload information$"):
    766         time.sleep(3)
    767         c.note("after reloading: " + str(c.dev.dump().texts()[:12]))
    768         c.check()
    769     else:
    770         c.note("no 'Reload information' entry in the menu")
    771     open_exchange_list(c)
    772     exchange_menu(c)
    773     if c.tap(r"(?i)^Treat as global$"):
    774         time.sleep(3)
    775         c.note("after treat-as-global: " + str(c.dev.dump().texts()[:12]))
    776         c.check()
    777         open_exchange_list(c)
    778         exchange_menu(c)
    779         after = c.dev.dump()
    780         c.note("menu now offers: " + str(after.texts()[:14]))
    781         if after.find(r"(?i)Stop treating as global") is None:
    782             c.note("WARNING: the exchange was not marked global; the menu is "
    783                    "unchanged, which is what the null master key bug looks like")
    784         c.tap(r"(?i)^Stop treating as global$")
    785         time.sleep(2)
    786         c.note("after stopping: " + str(c.dev.dump().texts()[:12]))
    787     else:
    788         c.note("no 'Treat as global' entry in the menu")
    789     c.check()
    790 
    791 
    792 @scenario("exchange_dev_add", setup="fresh", about="add the built-in development exchanges")
    793 def s_exchange_dev_add(c: Ctx) -> None:
    794     c.app.open_settings()
    795     c.app.scroll_to_text(r"(?i)^Add development payment services$")
    796     c.must_tap(r"(?i)^Add development payment services$")
    797     time.sleep(4)
    798     c.note("exchange list: " + str(c.dev.dump().texts()[:14]))
    799     c.check()
    800 
    801 
    802 @scenario("settings_walk", setup="funded", about="visit every settings row and toggle the switches")
    803 def s_settings_walk(c: Ctx) -> None:
    804     # Every row except the destructive ones and the two that talk to
    805     # demo.taler.net; those have their own scenarios.
    806     rows = [
    807         r"(?i)^Payment services$",
    808         r"(?i)^Bank accounts$",
    809         r"(?i)^Tax-deductible donations$",
    810         r"(?i)^Performance stats$",
    811         r"(?i)^Upgrade wallet database$",
    812         r"(?i)^App version$",
    813         r"(?i)^Wallet Core version$",
    814     ]
    815     for row in rows:
    816         c.app.open_settings()
    817         try:
    818             c.app.scroll_to_text(row, max_scrolls=10)
    819         except TimeoutError:
    820             c.note(f"row not present: {row}")
    821             continue
    822         if c.tap(row):
    823             time.sleep(1.5)
    824             c.check()
    825             c.note(f"visited {row}: {c.dev.dump().texts()[:6]}")
    826     # The switches: flip each one off and on again.
    827     for switch in (r"(?i)^Protect access to wallet$", r"(?i)^Developer mode$"):
    828         c.app.open_settings()
    829         try:
    830             screen = c.app.scroll_to_text(switch, max_scrolls=10)
    831         except TimeoutError:
    832             continue
    833         node = screen.find(switch)
    834         if node is None:
    835             continue
    836         width, _ = c.dev.size()
    837         _, y = node.center
    838         c.dev.tap(width - 100, y)
    839         time.sleep(2)
    840         c.check()
    841         c.dev.tap(width - 100, y)
    842         time.sleep(2)
    843         c.check()
    844     # Developer mode must survive the round trip, or later scenarios break.
    845     c.app.enable_dev_mode()
    846     c.check()
    847 
    848 
    849 def save_through_picker(c: Ctx, timeout: int = 30) -> bool:
    850     """Carry a "save as" through the system document picker.
    851 
    852     The wallet hands off to DocumentsUI, which prefills a file name and offers
    853     SAVE; without completing it the export never runs at all.
    854     """
    855     screen = c.see(r"(?i)^SAVE$|Files in Downloads", timeout=timeout)
    856     if screen is None:
    857         return False
    858     if not c.tap(r"(?i)^SAVE$", timeout=15):
    859         return False
    860     time.sleep(4)
    861     return True
    862 
    863 
    864 def pick_file_in_picker(c: Ctx, pattern: str = r"taler-wallet-db.*\.json",
    865                         timeout: int = 25) -> bool:
    866     """Choose the newest matching file in DocumentsUI and wait for the hand-back.
    867 
    868     Three things here are easy to get wrong, and all three were:
    869 
    870     * the picker labels the row with the file name *and* the thumbnail with
    871       "Preview the file <name>", so matching the name alone hits the preview;
    872     * it lists newest first, so "the last row" is the *oldest* file -- which
    873       for these exports is the one taken from an emptiest wallet, and
    874       importing it looks exactly like an import that lost everything;
    875     * `Screen.tap_target` hunts for a clickable ancestor or neighbour, and on
    876       these rows that lands somewhere that dismisses the picker without
    877       selecting, so the import never runs at all.
    878 
    879     So: skip the preview labels, pick the greatest *name* (they are
    880     timestamps), and tap the label's own centre.
    881 
    882     Note also that `adb shell ls /sdcard/Download` and the picker disagree:
    883     the shell sees its own scoped view, while the picker lists MediaStore,
    884     which still holds everything the app wrote.  Deleting old exports from the
    885     shell therefore does not clear the picker.
    886     """
    887     rx = re.compile(pattern, re.I)
    888     preview = re.compile(r"(?i)^preview\b")
    889     deadline = time.time() + timeout
    890     while time.time() < deadline:
    891         screen = c.dev.dump()
    892         rows = [n for n in screen.labelled()
    893                 if rx.search(n.label) and not preview.match(n.label.strip())]
    894         if rows:
    895             newest = max(rows, key=lambda n: n.label.strip())
    896             c.note(f"picking {newest.label.strip()!r} of "
    897                    f"{len(rows)} offered")
    898             c.dev.tap_node(newest, screen)
    899             break
    900         time.sleep(1.5)
    901     else:
    902         c.note(f"no file matching {pattern!r} in the picker: "
    903                + str(c.dev.dump().texts()[:12]))
    904         return False
    905     # Some pickers need the selection confirmed.
    906     for label in (r"(?i)^(OPEN|SELECT|DONE)$",):
    907         c.tap(label, timeout=4)
    908     # Handing back means the app is in the foreground again.
    909     deadline = time.time() + 25
    910     while time.time() < deadline:
    911         where = c.dev.dump().activity
    912         if where.startswith(PKG):
    913             return True
    914         time.sleep(2)
    915     c.note(f"the picker did not hand back to the wallet (now in {where}): "
    916            + str(c.dev.dump().texts()[:10]))
    917     return False
    918 
    919 
    920 @scenario("settings_export", setup="funded",
    921           about="database and log export, carried through the save dialog")
    922 def s_settings_export(c: Ctx) -> None:
    923     exported = []
    924     for row in (r"(?i)^Export database$", r"(?i)^Export raw database$",
    925                 r"(?i)^Debug log$"):
    926         c.app.open_settings()
    927         try:
    928             c.app.scroll_to_text(row, max_scrolls=10)
    929         except TimeoutError:
    930             c.note(f"row not present: {row}")
    931             continue
    932         c.tap(row)
    933         time.sleep(2)
    934         # The database exports warn first, because the file holds the money.
    935         if c.see(r"(?i)sensitive data|Export anyway", timeout=8):
    936             c.note(f"{row}: warned before exporting")
    937             c.tap(r"(?i)^Export anyway$", timeout=8)
    938         if save_through_picker(c):
    939             exported.append(row)
    940             c.check()
    941         else:
    942             c.note(f"{row}: no save dialog appeared")
    943             c.dev.back()
    944         time.sleep(1.5)
    945         c.check()
    946     listing = c.dev.shell("ls -la /sdcard/Download/", check=False)
    947     c.note(f"exported {len(exported)} file(s); Download now holds: "
    948            f"{[l.split()[-1] for l in listing.splitlines()[1:] if l.strip()][:5]}")
    949     c.app.home()
    950     c.ep.check_database()
    951 
    952 
    953 @scenario("settings_import", setup="funded",
    954           about="export the database, then import it back")
    955 def s_settings_import(c: Ctx) -> None:
    956     # Export first, so there is something to import.
    957     c.app.open_settings()
    958     c.app.scroll_to_text(r"(?i)^Export database$", max_scrolls=10)
    959     c.must_tap(r"(?i)^Export database$")
    960     if c.see(r"(?i)sensitive data|Export anyway", timeout=8):
    961         c.tap(r"(?i)^Export anyway$", timeout=8)
    962     if not save_through_picker(c):
    963         c.note("could not export, so there is nothing to import")
    964         return
    965     c.check()
    966 
    967     c.app.open_settings()
    968     c.app.scroll_to_text(r"(?i)^Import database$", max_scrolls=10)
    969     c.must_tap(r"(?i)^Import database$")
    970     if c.see(r"(?i)overwrite|Do you want", timeout=15):
    971         c.tap(r"(?i)^OK$|^Import$|^Yes$|^Continue$", timeout=10)
    972     screen = c.see(r"(?i)taler-wallet-db|Files in Downloads|Downloads", timeout=25)
    973     if screen is None:
    974         c.note("no document picker for the import")
    975         return
    976     c.note("picker: " + str(screen.texts()[:10]))
    977     if not pick_file_in_picker(c):
    978         c.dev.back()
    979         return
    980     time.sleep(8)
    981     c.note("after importing: " + str(c.dev.dump().texts()[:12]))
    982     log = c.dev.logcat()
    983     if "importDb" in log:
    984         c.note("importDb reached wallet-core")
    985     else:
    986         c.note("WARNING: the file was picked but importDb never ran")
    987     c.check()
    988     # The wallet has to still work on the imported database.
    989     c.back_to_home()
    990     rows = transaction_rows(open_transactions(c))
    991     c.note(f"{len(rows)} transactions after the import")
    992     c.check()
    993     c.ep.check_database()
    994 
    995 
    996 @scenario("settings_import_bad_file", setup="funded",
    997           about="import a file that is not a wallet database")
    998 def s_settings_import_bad_file(c: Ctx) -> None:
    999     """The import's error path.
   1000 
   1001     `SettingsManager.importDb` reads the chosen file as text, parses it as
   1002     JSON, and hands the object to wallet-core; anything that is not JSON
   1003     throws before the request and lands in `onDbImportError`.  The suite's
   1004     other import scenarios always pick a genuine export, so that branch -- and
   1005     the "Error importing database" it shows -- had never run.
   1006 
   1007     The file is written straight into Downloads and scanned into MediaStore,
   1008     because the picker lists MediaStore rather than the shell's view of the
   1009     directory.
   1010     """
   1011     name = f"sim-not-a-db-{int(time.time())}.json"
   1012     path = f"/sdcard/Download/{name}"
   1013     c.dev.shell(f"echo 'this is not a wallet database' > {path}", check=False)
   1014     c.dev.shell("content call --uri content://media/external/file "
   1015                 f"--method scan_file --arg {path}", check=False)
   1016     listed = c.dev.shell(f"ls -l {path}", check=False)
   1017     c.note(f"planted {name}: {listed.strip()[:100]}")
   1018     c.dev.logcat(clear=True)
   1019 
   1020     c.app.open_settings()
   1021     c.app.scroll_to_text(r"(?i)^Import database$", max_scrolls=10)
   1022     c.must_tap(r"(?i)^Import database$")
   1023     if c.see(r"(?i)overwrite|Do you want", timeout=15):
   1024         c.tap(r"(?i)^OK$|^Import$|^Yes$|^Continue$", timeout=10)
   1025     screen = c.see(r"(?i)Files in Downloads|Downloads|sim-not-a-db", timeout=25)
   1026     if screen is None:
   1027         c.note("no document picker for the import")
   1028         return
   1029     c.note("picker: " + str(screen.texts()[:10]))
   1030     if not pick_file_in_picker(c, pattern=r"sim-not-a-db.*\.json"):
   1031         c.note("could not pick the planted file; the picker showed "
   1032                + str(c.dev.dump().texts()[:12]))
   1033         c.dev.back()
   1034         return
   1035     # The error is a Toast (SettingsManager.onDbImportError), and LENGTH_LONG
   1036     # is about three and a half seconds: dumping at +6s missed it entirely and
   1037     # made it look as though nothing was reported.  Look early and repeatedly.
   1038     shown = False
   1039     after = c.dev.dump()
   1040     for _ in range(6):
   1041         after = c.dev.dump()
   1042         if after.find(r"(?i)Error importing database") is not None:
   1043             shown = True
   1044             break
   1045         time.sleep(1)
   1046     c.note("after importing rubbish: " + str(after.texts()[:12]))
   1047     log = c.dev.logcat()
   1048     logged = "Error importing db" in log
   1049     # Not an assertion: the feedback is a Toast, and a Toast is a system
   1050     # window that a hierarchy dump does not reliably contain.  "False" here
   1051     # means the harness could not see it, not that a user cannot.  What can
   1052     # be asserted is that the failure was detected at all.
   1053     c.note(f"the error toast was visible to the dump: {shown}")
   1054     c.note(f"the failure reached the log: {logged}")
   1055     if not logged:
   1056         c.note("WARNING: importing a non-database was not reported anywhere "
   1057                "this harness can see")
   1058     c.check()
   1059 
   1060     # And the wallet has to be usable afterwards: a failed import must not
   1061     # have touched the database it was going to replace.
   1062     c.back_to_home()
   1063     home = c.dev.dump()
   1064     c.note("home after the failed import: " + str(home.texts()[:12]))
   1065     if home.find(r"€|EUR") is None:
   1066         c.note("WARNING: no balance on the main screen after a failed import")
   1067     c.check()
   1068     c.dev.shell(f"rm -f {path}", check=False)
   1069     c.ep.check_database()
   1070 
   1071 
   1072 @scenario("settings_import_cancel", setup="funded", about="start a database import and cancel it")
   1073 def s_settings_import_cancel(c: Ctx) -> None:
   1074     c.app.open_settings()
   1075     c.app.scroll_to_text(r"(?i)^Import database$", max_scrolls=10)
   1076     c.must_tap(r"(?i)^Import database$")
   1077     asked = c.see(r"(?i)overwrite|Do you want|Cancel", timeout=20)
   1078     c.note("import prompt: " + str((asked or c.dev.dump()).texts()[:12]))
   1079     if asked:
   1080         c.tap(r"(?i)^Cancel$|^No$")
   1081     else:
   1082         c.note("WARNING: importing a database asked nothing before proceeding")
   1083     time.sleep(1.5)
   1084     c.dev.back()
   1085     c.note("back in settings: " + str(c.dev.dump().texts()[:10]))
   1086     c.check()
   1087 
   1088 
   1089 @scenario("settings_reset_confirmed", setup="funded",
   1090           about="confirm the wallet reset, which is the only caller of clearDb")
   1091 def s_settings_reset_confirmed(c: Ctx) -> None:
   1092     """Reset Wallet, carried through.
   1093 
   1094     `settings_reset_cancel` backs out of this dialog; nothing confirmed it, so
   1095     `clearDb` was one of the last wallet-core operations no scenario reached.
   1096 
   1097     The dialog is also worth looking at: the destructive action is the
   1098     *negative* button and Cancel is the *positive* one
   1099     (`settings/SettingsScreen.kt:361`), so Android draws "Reset" where
   1100     convention puts "Cancel".
   1101     """
   1102     c.app.open_settings()
   1103     c.app.scroll_to_text(r"(?i)^Reset Wallet", max_scrolls=12)
   1104     c.must_tap(r"(?i)^Reset Wallet")
   1105     dialog = c.require(r"(?i)really want to reset|lose all coins", timeout=20)
   1106     buttons = [(n.label.strip(), n.center[0]) for n in dialog.tappable()
   1107                if n.label.strip() in ("Reset", "Cancel")]
   1108     c.note(f"the reset dialog's buttons, left to right: "
   1109            + str(sorted(buttons, key=lambda b: b[1])))
   1110     c.check()
   1111     if not c.tap_button(r"(?i)^Reset$", timeout=15):
   1112         c.note("no Reset button in the dialog: " + str(dialog.texts()[:10]))
   1113         return
   1114     time.sleep(8)
   1115     after = c.dev.dump()
   1116     c.note("after resetting: " + str(after.texts()[:12]))
   1117     c.check()
   1118     log = c.dev.logcat()
   1119     if "clearDb" not in log:
   1120         c.note("WARNING: the reset did not reach clearDb")
   1121     # A reset wallet is an empty wallet.
   1122     balances = c.app.balances()
   1123     c.note(f"balance after the reset: {balances}")
   1124     if any(re.search(r"[1-9]", b) for b in balances):
   1125         c.note("WARNING: coins survived a wallet reset")
   1126     c.check()
   1127     c.ep.check_database()
   1128 
   1129 
   1130 @scenario("settings_reset_cancel", setup="funded", about="open the wallet reset dialog and cancel")
   1131 def s_settings_reset_cancel(c: Ctx) -> None:
   1132     c.app.open_settings()
   1133     c.app.scroll_to_text(r"(?i)^Reset Wallet", max_scrolls=10)
   1134     c.must_tap(r"(?i)^Reset Wallet")
   1135     if c.see(r"(?i)really want to reset|lose all coins|Cancel", timeout=20):
   1136         c.tap(r"(?i)^Cancel$|^No$")
   1137     time.sleep(2)
   1138     c.note("after cancelling the reset: " + str(c.dev.dump().texts()[:8]))
   1139     c.check()
   1140 
   1141 
   1142 @scenario("scan_manual_entry", setup="funded",
   1143           about="the scan screen's manual link entry, fed hostile input")
   1144 def s_scan_manual_entry(c: Ctx) -> None:
   1145     hostile = ["", "taler://", "not a uri at all",
   1146                corpus.MALFORMED["bad_base32"], corpus.MALFORMED["id_too_long"],
   1147                corpus.MALFORMED["unicode"], corpus.STRUCTURAL["pay"]]
   1148     for value in hostile:
   1149         try:
   1150             screen = c.app.open_scanner()
   1151         except TimeoutError:
   1152             c.note("could not open the scan screen: "
   1153                    + str(c.dev.dump().texts()[:10]))
   1154             return
   1155         fields = screen.editable() if screen else []
   1156         if not fields:
   1157             c.note("scan screen has no text field: " + str(screen.texts() if screen else None))
   1158             c.dev.back()
   1159             continue
   1160         c.dev.tap_node(fields[0], screen)
   1161         if value:
   1162             c.dev.type_text(value)
   1163         c.dev.key("KEYCODE_ENTER")
   1164         time.sleep(2.5)
   1165         c.check()
   1166         c.dev.back()
   1167         time.sleep(1)
   1168     c.check()
   1169 
   1170 
   1171 def tap_if_any(c: Ctx, patterns: tuple[str, ...], timeout: int = 6) -> bool:
   1172     """Tap the first of these labels that is present, if any."""
   1173     for pattern in patterns:
   1174         if c.tap(pattern, timeout=timeout):
   1175             return True
   1176     return False
   1177 
   1178 
   1179 def fill_account_note(c: Ctx, label: str = "Simulator account") -> bool:
   1180     """Fill the add-account form's required "Note" field.
   1181 
   1182     The form is a LazyColumn, so the note is often below the fold and absent
   1183     from the view hierarchy altogether -- filling "the last editable field"
   1184     then types into Town instead, leaves the note empty, and the submit button
   1185     stays disabled with nothing to show for it
   1186     (findings/add-account-note-is-required-but-unmarked.md).
   1187     """
   1188     try:
   1189         c.app.scroll_to_text(r"(?i)^Note$", max_scrolls=6)
   1190     except TimeoutError:
   1191         c.note("no Note field on this screen: " + str(c.dev.dump().texts()[:10]))
   1192         return False
   1193     fields = c.dev.dump().editable()
   1194     if not fields:
   1195         c.note("the add-account form has no editable fields")
   1196         return False
   1197     return c.fill(label, len(fields) - 1, clear=True)
   1198 
   1199 
   1200 def amount_value(amount: str) -> float:
   1201     """The numeric part of a "EUR:12.34" amount."""
   1202     try:
   1203         return float(amount.split(":", 1)[1])
   1204     except (IndexError, ValueError):
   1205         return float("nan")
   1206 
   1207 
   1208 @scenario("deposit", setup="funded", about="deposit coins back to a bank account")
   1209 def s_deposit(c: Ctx) -> None:
   1210     """A deposit that is checked, not just watched.
   1211 
   1212     This noted the bank balance before and after and passed either way, so it
   1213     reported "ok" for thirteen rounds while depositing nothing at all: the
   1214     balance was identical every time, because the payto link it used is one the
   1215     wallet refuses (findings/payto-link-only-accepts-iban.md).
   1216     """
   1217     before = c.bank.balance(*flows.WALLET_USER)
   1218     screen = flows.deposit_to_bank(c.app, c.env, "100")
   1219     c.note("after the deposit: " + str(screen.texts()[:12]))
   1220     c.check()
   1221     # The exchange has to aggregate and wire it, which is not instant.
   1222     deadline = time.monotonic() + 120
   1223     after = before
   1224     while time.monotonic() < deadline:
   1225         after = c.bank.balance(*flows.WALLET_USER)
   1226         if amount_value(after) > amount_value(before):
   1227             break
   1228         time.sleep(5)
   1229     c.note(f"bank balance {before} -> {after}")
   1230     if not amount_value(after) > amount_value(before):
   1231         raise RuntimeError(
   1232             f"the deposit did not reach the bank: balance stayed at {after} "
   1233             f"(screen: {c.dev.dump().texts()[:12]})")
   1234     c.check()
   1235 
   1236 
   1237 @scenario("deposit_payto_link", setup="funded",
   1238           about="a payto link for a non-IBAN account, which the wallet refuses")
   1239 def s_deposit_payto_link(c: Ctx) -> None:
   1240     """Pins the refusal, so a fix shows up here.
   1241 
   1242     `DepositManager.isSupportedPayToUri` accepts `payto://iban/...` only, so
   1243     the x-taler-bank account the wallet withdraws from -- and deposits to
   1244     perfectly well when it is picked from the account list -- cannot be reached
   1245     by a link.
   1246     """
   1247     screen = flows.deposit_via_payto_link(c.app, c.env)
   1248     refused = screen.find(r"(?i)Not a valid Taler link") is not None
   1249     c.note(f"x-taler-bank payto link refused: {refused} -- "
   1250            + str(screen.texts()[:10]))
   1251     if not refused:
   1252         c.note("the wallet now accepts an x-taler-bank payto link; "
   1253                "payto-link-only-accepts-iban.md may be fixed")
   1254     c.check()
   1255 
   1256 
   1257 # Everyday configuration changes, each of which restarts the app.  The wallet
   1258 # has to come back usable from all of them; one of them does not.
   1259 # Each change carries the API level the *driver* needs to make it: a per-app
   1260 # language is API 33+, so asking for one on an older device tests adb rather
   1261 # than the wallet, and reports a pass or a failure that means nothing.
   1262 CONFIG_CHANGES = (
   1263     ("app language", 33, "cmd locale set-app-locales {pkg} --locales de-DE",
   1264                          "cmd locale set-app-locales {pkg} --locales"),
   1265     ("dark mode", 29, "cmd uimode night yes", "cmd uimode night no"),
   1266     ("font size", 24, "settings put system font_scale 1.30",
   1267                       "settings put system font_scale 1.0"),
   1268     ("display size", 24, "wm density 480", "wm density reset"),
   1269 )
   1270 
   1271 
   1272 def undo_of(name: str) -> str:
   1273     for n, _, _, undo in CONFIG_CHANGES:
   1274         if n == name:
   1275             return undo
   1276     raise KeyError(name)
   1277 
   1278 
   1279 INIT_ERROR = (r"(?i)Initialization error|Initialisierungsfehler"
   1280               r"|error occurred while starting|Fehler aufgetreten")
   1281 
   1282 
   1283 @scenario("config_changes", setup="funded",
   1284           about="change the language, theme, font and display size mid-flow",
   1285           expects=("error-screen", "internal-error-code"))
   1286 def s_config_changes(c: Ctx) -> None:
   1287     """Does the wallet survive what Android does to every app?
   1288 
   1289     Each of these recreates the activity -- and restarts the app -- while the
   1290     wallet is open.  Changing the language loses the race for the SQLite
   1291     database and dead-ends on the Initialization error screen
   1292     (`config-change-locks-the-wallet-out-of-its-database.md`), so the others
   1293     are worth measuring in the same place.
   1294     """
   1295     pkg = c.dev.pkg
   1296     broken: list[str] = []
   1297     try:
   1298         for name, needs_api, apply_cmd, _ in CONFIG_CHANGES:
   1299             if c.dev.sdk_int < needs_api:
   1300                 c.note(f"{name}: skipped, the driver needs API {needs_api} "
   1301                        f"and this device is API {c.dev.sdk_int}")
   1302                 continue
   1303             # A settings sub-screen keeps the wallet busy while the change
   1304             # lands, which is where this was first seen.
   1305             c.app.open_settings()
   1306             c.app.scroll_to_text(r"(?i)^Contacts$", max_scrolls=12)
   1307             c.tap(r"(?i)^Contacts$", timeout=20)
   1308             time.sleep(2)
   1309             c.dev.shell(apply_cmd.format(pkg=pkg), check=False)
   1310             time.sleep(9)
   1311             screen = c.dev.dump()
   1312             if screen.find(INIT_ERROR) is not None:
   1313                 broken.append(name)
   1314                 c.note(f"{name}: the wallet came back on its init error screen: "
   1315                        + str(screen.texts()[:4]))
   1316             else:
   1317                 c.note(f"{name}: survived -- " + str(screen.texts()[:8]))
   1318             c.check()
   1319             # Undo before the next one, so a failure is attributable.
   1320             c.dev.shell(undo_of(name).format(pkg=pkg), check=False)
   1321             time.sleep(6)
   1322             c.dev.stop()
   1323             time.sleep(2)
   1324             c.dev.launch()
   1325             time.sleep(8)
   1326             back = c.dev.dump()
   1327             if back.find(INIT_ERROR) is not None:
   1328                 c.note(f"WARNING: still on the init error screen after undoing "
   1329                        f"{name} and relaunching")
   1330             c.check()
   1331         c.note(f"configuration changes the wallet did not survive: {broken}")
   1332     finally:
   1333         for name, needs_api, _, undo in CONFIG_CHANGES:
   1334             if c.dev.sdk_int >= needs_api:
   1335                 c.dev.shell(undo.format(pkg=pkg), check=False)
   1336 
   1337 
   1338 @scenario("abandon_aborting_deposit", setup="funded",
   1339           about="abort a deposit with no network, then abandon it",
   1340           # The abandoned deposit shows a fee on a transaction that failed,
   1341           # which is recorded under aborted-credit-shows-the-whole-amount-as-fee.md
   1342           # and may be correct, so it does not need flagging every round.
   1343           expects=("fee-on-dead-transaction", "unfinished-transaction"))
   1344 def s_abandon_aborting_deposit(c: Ctx) -> None:
   1345     """The only reachable "Abandon".
   1346 
   1347     wallet-core offers TransactionAction.Fail -- "Abandon", the one button
   1348     that calls failTransaction -- for a deposit or peer-push that is
   1349     *aborting*, and for little else: a withdrawal waiting on the bank never
   1350     offers it, which is what `withdraw_abandon` keeps recording.  An abort
   1351     against a healthy exchange finishes in a blink, so the transaction only
   1352     sits in that state while the wallet is offline, and the dialog's own
   1353     warning ("Funds still in transit WILL GET LOST") is exactly what is being
   1354     tested.
   1355     """
   1356     # The network goes away between entering the amount and submitting: a
   1357     # deposit against a reachable exchange completes in under four seconds, so
   1358     # taking the network afterwards only ever found a finished transaction.
   1359     def go_offline() -> None:
   1360         c.dev.shell("cmd connectivity airplane-mode enable", check=False)
   1361         time.sleep(3)
   1362 
   1363     screen = flows.deposit_to_bank(c.app, c.env, "100", before_submit=go_offline)
   1364     c.note("the deposit, submitted offline: " + str(screen.texts()[:12]))
   1365     c.check()
   1366     if not c.tap(r"(?i)^Abort$", timeout=20):
   1367         c.note("no Abort on the deposit: " + str(c.dev.dump().texts()[:14]))
   1368         c.dev.shell("cmd connectivity airplane-mode disable", check=False)
   1369         return
   1370     if c.see(r"(?i)Abort transaction|Are you sure", timeout=10):
   1371         c.tap(r"(?i)^Abort$|^OK$|^Yes$")
   1372     time.sleep(5)
   1373     # abortTransaction's onSuccess navigates back, so the detail screen -- and
   1374     # with it every action button -- is gone by now; the transaction has to be
   1375     # reopened to see what it offers.
   1376     rows = transaction_rows(open_transactions(c))
   1377     if rows:
   1378         c.dev.tap_node(rows[0])
   1379         time.sleep(3)
   1380     aborting = c.dev.dump()
   1381     c.note("the aborting deposit, reopened: " + str(aborting.texts()[:16]))
   1382     c.check()
   1383     if not c.tap(r"(?i)^Abandon$", timeout=20):
   1384         c.note("Abandon not offered on the aborting deposit; it offers "
   1385                + str([n.label for n in aborting.tappable() if n.label][:10]))
   1386         c.dev.shell("cmd connectivity airplane-mode disable", check=False)
   1387         return
   1388     dialog = c.dev.dump()
   1389     c.note("the abandon dialog: " + str(dialog.texts()[:10]))
   1390     c.tap(r"(?i)^Abandon$|^OK$|^Yes$")
   1391     time.sleep(4)
   1392     c.note("after abandoning: " + str(c.dev.dump().texts()[:14]))
   1393     c.check()
   1394     # Back online: an abandoned transaction must stay abandoned, and the
   1395     # balance must not count the coins twice.
   1396     c.dev.shell("cmd connectivity airplane-mode disable", check=False)
   1397     time.sleep(10)
   1398     c.note("after reconnecting: " + str(c.dev.dump().texts()[:14]))
   1399     c.check()
   1400     c.back_to_home()
   1401     c.note("balance afterwards: " + str(c.dev.dump().texts()[:10]))
   1402     c.check()
   1403     c.ep.check_database()
   1404 
   1405 
   1406 @scenario("peer_push_receive", setup="fresh", about="receive a peer push payment from the CLI wallet")
   1407 def s_peer_push(c: Ctx) -> None:
   1408     screen = flows.peer_receive(c.app, c.env, "EUR:1", c.cli)
   1409     c.note("the prompt: " + str(screen.texts()[:12]))
   1410     # The prompt is still on screen right after the tap; accepting is a
   1411     # round trip to the exchange, and only its completion reaches
   1412     # confirmPeerPushCredit and the credit transaction's own screen.
   1413     for _ in range(12):
   1414         time.sleep(3)
   1415         now = c.dev.dump()
   1416         if now.find(r"(?i)completed successfully|This transaction is pending|€") is not None \
   1417                 and now.find(r"(?i)Do you want to receive") is None:
   1418             break
   1419     c.note("after accepting: " + str(c.dev.dump().texts()[:14]))
   1420     c.check()
   1421     # The balance has to move, and this has to *fail* when it does not: the
   1422     # old check asked for a screen with no "€" on it, which a zero balance of
   1423     # "€0.00" never is, so a payment that never arrived read as success for
   1424     # every round of this campaign.
   1425     deadline = time.monotonic() + 90
   1426     shown: list[str] = []
   1427     while time.monotonic() < deadline:
   1428         shown = c.app.balances()
   1429         if any(re.search(r"[1-9]", s) for s in shown):
   1430             break
   1431         time.sleep(5)
   1432     c.note(f"balance after receiving: {shown}")
   1433     if not any(re.search(r"[1-9]", s) for s in shown):
   1434         raise RuntimeError(
   1435             f"the received push payment did not reach the balance: {shown} "
   1436             f"(screen: {c.dev.dump().texts()[:12]})")
   1437     c.check()
   1438     # The credit's own detail screen: nothing had opened it, so
   1439     # TransactionPeerPushCreditComposable had never rendered.
   1440     rows = transaction_rows(open_transactions(c))
   1441     if rows:
   1442         c.dev.tap_node(rows[0])
   1443         time.sleep(2.5)
   1444         detail = c.dev.dump()
   1445         c.note("the received push, in detail: " + str(detail.texts()[:16]))
   1446         c.check()
   1447         c.app.scroll_to_text(r"(?i)^Show JSON$|^Delete$", max_scrolls=4)
   1448         c.check()
   1449     c.ep.check_database()
   1450 
   1451 
   1452 @scenario("peer_pull_pay", setup="funded", about="pay an invoice the CLI wallet issued")
   1453 def s_peer_pull(c: Ctx) -> None:
   1454     flows.peer_pay_invoice(c.app, c.env, "EUR:1", c.cli)
   1455     time.sleep(3)
   1456     c.note("after paying the invoice: " + str(c.dev.dump().texts()[:10]))
   1457     c.check()
   1458 
   1459 
   1460 @scenario("balances_screens", setup="paid", about="balances, tokens and donation statements")
   1461 def s_balances(c: Ctx) -> None:
   1462     c.back_to_home()
   1463     for label in (r"(?i)^Balances$", r"(?i)^Other assets$", r"(?i)^Donation statements$",
   1464                   r"(?i)^Contacts$"):
   1465         c.back_to_home()
   1466         if c.tap(label, timeout=10):
   1467             time.sleep(1.5)
   1468             c.note(f"{label}: {c.dev.dump().texts()[:8]}")
   1469             c.check()
   1470     c.check()
   1471 
   1472 
   1473 @scenario("peer_send", setup="funded", about="wallet sends money to the CLI wallet (OutgoingPush)")
   1474 def s_peer_send(c: Ctx) -> None:
   1475     c.back_to_home()
   1476     c.must_tap(r"(?i)^Send$", timeout=30)
   1477     c.require(r"(?i)Send money|Amount to send|Purpose", timeout=30)
   1478     c.set_amount("€5.00", "500")
   1479     c.check()
   1480     # Purpose and expiry are optional; touch them so their code runs.
   1481     c.tap(r"(?i)^Purpose$", timeout=6)
   1482     c.tap(r"(?i)Expires in|1 week|30 days", timeout=6)
   1483     c.must_tap(r"(?i)^Send ", timeout=30)
   1484     c.see(r"(?i)Scan this QR code to receive|copy and send this URI", timeout=60)
   1485     uri = c.uri_from_logcat("pay-push")
   1486     c.note(f"push uri: {uri[:70]}")
   1487     # The app's side of the flow is what is under test; whether the CLI peer
   1488     # can accept depends on its wallet-core being compatible with this
   1489     # exchange, so a failure there is recorded rather than raised.
   1490     try:
   1491         flows.fund_peer(c.cli, c.env, "EUR:5")
   1492         result = c.cli.accept_push(uri)
   1493         c.note(f"peer accepted: {str(result)[:200]}")
   1494     except Exception as e:
   1495         c.note(f"peer could not accept (counterparty problem): {str(e)[:220]}")
   1496     time.sleep(4)
   1497     c.back_to_home()
   1498     rows = transaction_rows(open_transactions(c))
   1499     c.note(f"transactions after sending: {[n.label[:24] for n in rows]}")
   1500     c.check()
   1501     c.ep.check_database()
   1502 
   1503 
   1504 @scenario("peer_request", setup="funded", about="wallet invoices the CLI wallet (OutgoingPull)")
   1505 def s_peer_request(c: Ctx) -> None:
   1506     c.back_to_home()
   1507     c.must_tap(r"(?i)^Request$", timeout=30)
   1508     c.require(r"(?i)Request money|Amount to receive|Amount requested", timeout=30)
   1509     c.set_amount("€5.00", "500")
   1510     c.check()
   1511     c.must_tap(r"(?i)^Request ", timeout=30)
   1512     c.see(r"(?i)Scan this QR code to pay|copy and send this URI", timeout=60)
   1513     uri = c.uri_from_logcat("pay-pull")
   1514     c.note(f"pull uri: {uri[:70]}")
   1515     try:
   1516         flows.fund_peer(c.cli, c.env, "EUR:5")
   1517         result = c.cli.pay_pull(uri)
   1518         c.note(f"peer paid the invoice: {str(result)[:160]}")
   1519     except Exception as e:
   1520         c.note(f"peer could not pay (counterparty problem): {str(e)[:200]}")
   1521     time.sleep(4)
   1522     c.check()
   1523 
   1524 
   1525 @scenario("deposit_flow", setup="funded",
   1526           about="the Deposit button: amount, account selection, IBAN entry")
   1527 def s_deposit_flow(c: Ctx) -> None:
   1528     c.back_to_home()
   1529     c.must_tap(r"(?i)^Deposit$", timeout=30)
   1530     # The account comes first: the amount field only appears once a target
   1531     # account has been picked.
   1532     screen = c.require(r"(?i)deposit to bank account|Manage bank accounts|x-taler-bank",
   1533                        timeout=30)
   1534     c.note("account step: " + str(screen.texts()[:10]))
   1535     account = screen.find(r"(?i)^wallet\d+$") or screen.find(r"(?i)x-taler-bank")
   1536     if account is not None:
   1537         c.dev.tap_node(account, screen)
   1538         time.sleep(2)
   1539     c.require(r"(?i)Amount to deposit|Make deposit", timeout=25)
   1540     c.set_amount("€5.00", "500")
   1541     c.check()
   1542     c.tap(r"(?i)^Check fees$", timeout=8)
   1543     c.tap(r"(?i)^Make deposit$|^Deposit$|^Next$|^Continue$", timeout=15)
   1544     # The account manager, with the IBAN form behind "Add account".
   1545     if c.see(r"(?i)Select bank account|Known bank accounts|Add account|Manage bank accounts",
   1546              timeout=20):
   1547         c.tap(r"(?i)^Manage bank accounts$", timeout=8)
   1548         if c.tap(r"(?i)^Add account$", timeout=15):
   1549             c.see(r"(?i)IBAN|Account holder|x-taler-bank", timeout=20)
   1550             c.check()
   1551             c.fill("Wallet One", 0)
   1552             c.fill("DE89370400440532013000", 1)
   1553             c.tap(r"(?i)^Save$|^Add$|^OK$|^Continue$", timeout=15)
   1554             time.sleep(2)
   1555             c.check()
   1556     c.tap(r"(?i)^Make deposit$|^Deposit$", timeout=20)
   1557     time.sleep(4)
   1558     c.note("after deposit attempt: " + str(c.dev.dump().texts()[:10]))
   1559     c.check()
   1560 
   1561 
   1562 @scenario("bank_accounts", setup="funded", about="Settings - Bank accounts: add, edit, forget")
   1563 def s_bank_accounts(c: Ctx) -> None:
   1564     c.app.open_settings()
   1565     c.app.scroll_to_text(r"(?i)^Bank accounts$")
   1566     c.must_tap(r"(?i)^Bank accounts$")
   1567     c.require(r"(?i)Known bank accounts|No bank accounts saved|Add account", timeout=25)
   1568     c.check()
   1569     if c.tap(r"(?i)^Add account$", timeout=20):
   1570         c.see(r"(?i)IBAN|Account holder", timeout=20)
   1571         # The form opens on the x-taler-bank tab, whose fields are a host
   1572         # dropdown, holder, account and note -- so filling "field 1" with an
   1573         # IBAN typed it into the account name.  Pick the tab first.
   1574         c.tap(r"(?i)^IBAN$", timeout=10)
   1575         time.sleep(1.5)
   1576         # Wrong IBAN first: the form should say so rather than accept it.
   1577         c.fill("Test Holder", 0, clear=True)
   1578         c.fill("NOT-AN-IBAN", 1, clear=True)
   1579         # "Note" carries no "(optional)" but the submit button is disabled
   1580         # without it (findings/add-account-note-is-required-but-unmarked.md),
   1581         # so it has to be filled or nothing can ever be added.
   1582         fill_account_note(c, "Test account")
   1583         # The submit button carries the same string as the title and the add
   1584         # icon, so it has to be picked as a button, not as a label.
   1585         submitted = c.tap_button(r"(?i)^Add account$|^Save$|^OK$", timeout=10)
   1586         time.sleep(1.5)
   1587         c.note(f"invalid IBAN (submit tappable: {submitted}): "
   1588                + str(c.dev.dump().texts()[:10]))
   1589         c.check()
   1590         # Without clear=True this appends, leaving "NOT-AN-IBANDE89370…",
   1591         # which keeps the submit button disabled: no account was ever added.
   1592         c.fill("DE89370400440532013000", 1, clear=True)
   1593         c.tap_button(r"(?i)^Add account$|^Save$|^OK$", timeout=10)
   1594         time.sleep(3)
   1595         listed = c.dev.dump()
   1596         c.note("after adding: " + str(listed.texts()[:12]))
   1597         if listed.find(r"DE89|370400440532013000|Test Holder") is None:
   1598             c.note("WARNING: the account does not appear in the list")
   1599         c.check()
   1600     # Edit whatever is listed now.  There is no "Edit" label to tap: the row
   1601     # itself is clickable and opens the add screen with the account's id,
   1602     # which is the only thing that ever calls getBankAccountById.
   1603     if c.tap(r"(?i)Test Holder|DE89|370400440532013000", timeout=10):
   1604         if c.see(r"(?i)^Edit account$", timeout=20):
   1605             edit = c.dev.dump()
   1606             c.note("the edit form: " + str(edit.texts()[:14]))
   1607             if edit.find(r"(?i)Test Holder") is None:
   1608                 c.note("WARNING: the edit form did not load the account")
   1609             # Change the holder and save, then check the list shows the change.
   1610             c.fill("Edited Holder", 0, clear=True)
   1611             c.tap_button(r"(?i)^Save$|^Edit account$|^OK$", timeout=10)
   1612             time.sleep(3)
   1613             c.note("after saving: " + str(c.dev.dump().texts()[:12]))
   1614         else:
   1615             c.note("tapping the account row did not open the edit form: "
   1616                    + str(c.dev.dump().texts()[:12]))
   1617         c.check()
   1618     c.back_to_home()
   1619     c.app.open_settings()
   1620     c.app.scroll_to_text(r"(?i)^Bank accounts$")
   1621     c.must_tap(r"(?i)^Bank accounts$")
   1622     c.require(r"(?i)Known bank accounts|No bank accounts saved|Add account", timeout=25)
   1623     if c.tap(r"(?i)^Delete$|^Forget", timeout=10):
   1624         if c.see(r"(?i)Forget account|really wish to forget", timeout=10):
   1625             c.tap(r"(?i)^Forget$|^OK$|^Yes$|^Delete$")
   1626     time.sleep(2)
   1627     c.check()
   1628 
   1629 
   1630 @scenario("manual_withdraw_transfer", setup="funded",
   1631           about="the Withdraw button: manual wire transfer details and QR codes")
   1632 def s_manual_withdraw_transfer(c: Ctx) -> None:
   1633     c.back_to_home()
   1634     c.must_tap(r"(?i)^Withdraw$", timeout=30)
   1635     c.require(r"(?i)Amount to withdraw|Select target bank account|Payment service",
   1636               timeout=30)
   1637     c.fill("5")
   1638     c.check()
   1639     c.tap(r"(?i)Restrict usage to age|Unrestricted", timeout=6)
   1640     c.accept_tos()
   1641     c.must_tap(r"(?i)^Withdraw$|Confirm withdrawal", timeout=30)
   1642     if c.see(r"(?i)Wire transfer instructions|Subject|IBAN|Recipient|Account", timeout=60):
   1643         c.note("manual withdrawal instructions reached")
   1644         c.check()
   1645         # Each of these used to be tried and dropped on the floor, so a button
   1646         # that stopped working looked exactly like one that is not offered for
   1647         # this account type.  Say which happened.
   1648         reached = []
   1649         for label in (r"(?i)Wire transfer QR codes", r"(?i)EPC QR", r"(?i)Swiss QR bill",
   1650                       r"(?i)Open in banking app"):
   1651             try:
   1652                 c.app.scroll_to_text(label, max_scrolls=6)
   1653             except TimeoutError:
   1654                 c.note(f"{label}: not offered on this screen")
   1655                 continue
   1656             if not c.tap(label, timeout=8):
   1657                 c.note(f"{label}: on screen but the tap did not take")
   1658                 continue
   1659             time.sleep(1.5)
   1660             reached.append(label)
   1661             c.note(f"{label}: " + str(c.dev.dump().texts()[:10]))
   1662             c.check()
   1663             # "Wire transfer QR codes" is the one that navigates away, to the
   1664             # transfer screen with showQrCodes set -- the only way that branch
   1665             # of ScreenTransfer runs.
   1666             if "QR codes" in label:
   1667                 if c.see(r"(?i)you can scan one of these QR codes|share this QR code",
   1668                          timeout=15) is None:
   1669                     c.note("the QR code screen did not show its own text: "
   1670                            + str(c.dev.dump().texts()[:12]))
   1671                 else:
   1672                     c.note("the QR variant of the transfer screen rendered")
   1673                 c.check()
   1674                 c.dev.back()
   1675                 time.sleep(1.5)
   1676         c.note(f"transfer actions reached: {reached}")
   1677     c.note("screen: " + str(c.dev.dump().texts()[:12]))
   1678     c.check()
   1679 
   1680 
   1681 @scenario("tokens_screen", setup="paid", about="the Other assets / token list screen")
   1682 def s_tokens(c: Ctx) -> None:
   1683     c.back_to_home()
   1684     # The main screen's own labels: "Discounts" and "Passes" are the token
   1685     # views, "Donation statements" the donau receipts.
   1686     for label in (r"(?i)^Discounts$", r"(?i)^Passes$", r"(?i)^Donation statements$"):
   1687         c.back_to_home()
   1688         try:
   1689             c.app.scroll_to_text(label, max_scrolls=5)
   1690         except TimeoutError:
   1691             c.note(f"{label} not on the main screen")
   1692             continue
   1693         c.tap(label, timeout=10)
   1694         time.sleep(2)
   1695         c.note(f"{label}: {c.dev.dump().texts()[:10]}")
   1696         c.check()
   1697         for tab in (r"(?i)^Available$", r"(?i)^Expired$"):
   1698             c.tap(tab, timeout=6)
   1699             c.check()
   1700     c.check()
   1701 
   1702 
   1703 @scenario("donau_setup", setup="funded", about="configure the donation tax authority")
   1704 def s_donau(c: Ctx) -> None:
   1705     c.app.open_settings()
   1706     c.app.scroll_to_text(r"(?i)^Tax-deductible donations$")
   1707     c.must_tap(r"(?i)^Tax-deductible donations$")
   1708     c.require(r"(?i)tax authority|Donor tax payer ID|donation", timeout=25)
   1709     c.check()
   1710     if c.tap(r"(?i)^Select tax authority$", timeout=15):
   1711         time.sleep(2)
   1712         c.check()
   1713         c.tap(r"(?i)localhost:8079|Bern", timeout=10)
   1714         c.tap_button(r"(?i)^Setup tax payer ID$", timeout=10)
   1715         time.sleep(2)
   1716     # The form has two fields in this order: the authority's URL, then the tax
   1717     # payer ID.  Save stays disabled until both are filled, which is why
   1718     # filling only the first one made the tap do nothing at all.
   1719     c.fill(c.env.donau, 0)
   1720     c.fill("TAXID-12345", 1)
   1721     time.sleep(1)
   1722     saved = c.tap_button(r"(?i)^Save$", timeout=15)
   1723     time.sleep(4)
   1724     screen = c.dev.dump()
   1725     c.note(f"after donau setup (save tappable: {saved}): " + str(screen.texts()[:12]))
   1726     if screen.find(r"(?i)configured successfully|Tax-deductible donations") is None:
   1727         c.note("WARNING: the tax authority was not accepted")
   1728     c.check()
   1729 
   1730 
   1731 @scenario("contacts_alias", setup="funded", about="contacts and alias registration")
   1732 def s_contacts(c: Ctx) -> None:
   1733     c.back_to_home()
   1734     if not c.tap(r"(?i)^Contacts$", timeout=15):
   1735         c.app.open_settings()
   1736         try:
   1737             c.app.scroll_to_text(r"(?i)^Contacts$|Alias Registration", max_scrolls=10)
   1738             c.tap(r"(?i)^Contacts$|Alias Registration", timeout=10)
   1739         except TimeoutError:
   1740             c.note("no way into contacts from home or settings")
   1741             return
   1742     screen = c.see(r"(?i)Contacts|Alias", timeout=20)
   1743     c.note("contacts screen: " + str((screen or c.dev.dump()).texts()[:14]))
   1744     c.check()
   1745     if c.tap(r"(?i)Alias Registration|^Register", timeout=15):
   1746         c.see(r"(?i)Alias Type|Alias|Duration", timeout=20)
   1747         c.fill("simulator@example.com")
   1748         c.tap(r"(?i)^Register Alias$", timeout=15)
   1749         time.sleep(3)
   1750         c.note("after alias registration: " + str(c.dev.dump().texts()[:10]))
   1751     c.check()
   1752 
   1753 
   1754 @scenario("transactions_bulk_delete", setup="paid",
   1755           about="selection mode: long-press, Select All, delete the lot")
   1756 def s_bulk_delete(c: Ctx) -> None:
   1757     """The main screen's rows do not select, and that is deliberate.
   1758 
   1759     This scenario used to long-press a row here, look for "Select All", and
   1760     return with "long press did not open selection mode" -- every round, while
   1761     counting as a pass.  It never could: `BalancesPagerComposable`'s
   1762     `BalanceRecentTransactions` builds each `TransactionRow` with
   1763     `selectionMode = false` and `onTransactionSelect = {}`, so a long press on
   1764     the main screen is a no-op by construction.  Selection and bulk deletion
   1765     live on the dedicated screen behind the "All" chip, which is what
   1766     `transactions_screen_selection` drives.
   1767 
   1768     What is left here is worth pinning: a long press must do *nothing* -- not
   1769     open a detail screen, not select, not crash.
   1770     """
   1771     screen = open_transactions(c)
   1772     rows = transaction_rows(screen)
   1773     if not rows:
   1774         raise RuntimeError(f"no transaction rows; screen: {screen.texts()}")
   1775     before = screen.signature()
   1776     c.dev.long_press(rows[0])
   1777     time.sleep(2)
   1778     after = c.dev.dump()
   1779     c.note("after a long press on the main screen: " + str(after.texts()[:12]))
   1780     if after.find(r"(?i)^Select All$") is not None:
   1781         c.note("selection mode opened on the main screen, which it is not "
   1782                "built to do -- the list's arguments must have changed")
   1783     elif after.signature() != before:
   1784         c.note("the long press changed the screen: " + str(after.texts()[:12]))
   1785     else:
   1786         c.note("the long press did nothing, as the main screen's rows intend")
   1787     c.check()
   1788     c.ep.check_database()
   1789 
   1790 
   1791 @scenario("transactions_screen_selection", setup="paid",
   1792           about="selection mode on the dedicated transactions screen")
   1793 def s_transactions_screen_selection(c: Ctx) -> None:
   1794     """The other transaction list.
   1795 
   1796     `transactions_bulk_delete` works on the main screen's "Recent
   1797     transactions" section.  The **dedicated** screen behind the "All" chip is
   1798     `TransactionsScreen.kt`, and its selection mode -- select all, leave
   1799     selection mode, and the delete-selected dialog -- is the uncovered half of
   1800     that file.
   1801     """
   1802     c.back_to_home()
   1803     try:
   1804         c.app.scroll_to_text(r"(?i)^All$", max_scrolls=6)
   1805     except TimeoutError:
   1806         c.note("no All chip on the main screen: " + str(c.dev.dump().texts()[:14]))
   1807         return
   1808     c.must_tap(r"(?i)^All$", timeout=15)
   1809     time.sleep(2)
   1810     screen = c.dev.dump()
   1811     c.note("after the All chip: " + str(screen.texts()[:14]))
   1812     if screen.find(r"(?i)^Transactions$") is None:
   1813         c.note("the All chip did not open the transactions screen")
   1814         c.check()
   1815         return
   1816     c.check()
   1817 
   1818     rows = transaction_rows(screen, header=r"(?i)^Transactions$",
   1819                             signed_only=True)
   1820     if not rows:
   1821         c.note("no rows on the transactions screen: " + str(screen.texts()[:14]))
   1822         c.check()
   1823         return
   1824     c.dev.long_press(rows[0])
   1825     time.sleep(2)
   1826     screen = c.dev.dump()
   1827     c.note("selection mode: " + str(screen.texts()[:14]))
   1828     if screen.find(r"(?i)^Select All$") is None:
   1829         c.note("long press did not open selection mode here either")
   1830         c.check()
   1831         return
   1832     c.must_tap(r"(?i)^Select All$", timeout=15)
   1833     time.sleep(1.5)
   1834     c.note("after select all: " + str(c.dev.dump().texts()[:14]))
   1835     c.check()
   1836 
   1837     # Leaving selection mode is an unnamed icon button in the app bar
   1838     # (TransactionsScreen.kt:112 passes contentDescription = null), so it can
   1839     # only be found by position: the top-left clickable.
   1840     screen = c.dev.dump()
   1841     unnamed = [n for n in screen.unnamed_clickables() if n.bounds[1] < 400]
   1842     c.note(f"{len(unnamed)} unnamed clickable(s) in the app bar: "
   1843            + str([n.bounds for n in unnamed][:4]))
   1844     if unnamed:
   1845         leftmost = min(unnamed, key=lambda n: n.bounds[0])
   1846         c.dev.tap(*leftmost.center)
   1847         time.sleep(1.5)
   1848         back = c.dev.dump()
   1849         c.note("after closing selection mode: " + str(back.texts()[:12]))
   1850         if back.find(r"(?i)^Select All$") is not None:
   1851             c.note("WARNING: still in selection mode")
   1852         c.check()
   1853 
   1854     # Round two: select all and delete, through the confirmation dialog.
   1855     screen = c.dev.dump()
   1856     rows = transaction_rows(screen, header=r"(?i)^Transactions$",
   1857                             signed_only=True)
   1858     if not rows:
   1859         c.note("no rows left to select")
   1860         c.check()
   1861         return
   1862     c.dev.long_press(rows[0])
   1863     time.sleep(2)
   1864     if not c.tap(r"(?i)^Select All$", timeout=10):
   1865         c.note("could not re-enter selection mode")
   1866         c.check()
   1867         return
   1868     time.sleep(1)
   1869     if not c.tap(r"(?i)^Delete$", timeout=15):
   1870         c.note("no Delete in the selection app bar: "
   1871                + str(c.dev.dump().texts()[:12]))
   1872         c.check()
   1873         return
   1874     dialog = c.see(r"(?i)Delete transactions|Are you sure you want to remove",
   1875                    timeout=15)
   1876     c.note("the delete dialog: "
   1877            + (str(dialog.texts()[:10]) if dialog else "did not appear"))
   1878     if dialog is not None:
   1879         c.must_tap(r"(?i)^Delete$|^OK$|^Yes$", timeout=10)
   1880         time.sleep(3)
   1881     left = transaction_rows(c.dev.dump(), header=r"(?i)^Transactions$",
   1882                             signed_only=True)
   1883     c.note(f"rows after deleting the selection: {len(left)}")
   1884     c.check()
   1885     c.ep.check_database()
   1886 
   1887 
   1888 @scenario("transactions_filter", setup="paid", about="the transaction list filter chip")
   1889 def s_tx_filter(c: Ctx) -> None:
   1890     open_transactions(c)
   1891     for _ in range(3):
   1892         if not c.tap(r"(?i)^All$", timeout=10):
   1893             break
   1894         time.sleep(1.5)
   1895         screen = c.dev.dump()
   1896         c.note("filter menu: " + str(screen.texts()[:12]))
   1897         c.check()
   1898         # Pick whatever option the menu offers, then come back to All.
   1899         if not c.tap(r"(?i)pending|final|complete|incoming|outgoing", timeout=8):
   1900             c.dev.back()
   1901             break
   1902         time.sleep(1.5)
   1903         c.check()
   1904     c.check()
   1905 
   1906 
   1907 def open_mailbox(c: Ctx) -> None:
   1908     c.app.open_settings()
   1909     c.app.scroll_to_text(r"(?i)^Mailbox$", max_scrolls=10)
   1910     c.must_tap(r"(?i)^Mailbox$")
   1911     c.require(r"(?i)mailbox|message|P2P|empty|Loading", timeout=25)
   1912 
   1913 
   1914 @scenario("mailbox", setup="funded", about="the P2P messaging mailbox screen")
   1915 def s_mailbox(c: Ctx) -> None:
   1916     """The mailbox screen and both of its dialogs.
   1917 
   1918     The screen has three actions in its app bar -- the address, the URL
   1919     configuration and a refresh -- and this used to tap for "Add"/"New"/"+"
   1920     and "refresh", which matched only the last of them.  The two dialogs are
   1921     half of `MailboxScreen.kt`'s uncovered lines, and the address one is the
   1922     only caller of its clipboard copy.
   1923     """
   1924     open_mailbox(c)
   1925     screen = c.dev.dump()
   1926     c.note("mailbox: " + str(screen.texts()[:14]))
   1927     c.check()
   1928 
   1929     # "Show Mailbox Address" exists only once the mailbox has registered.
   1930     if c.tap(r"(?i)^Show Mailbox Address$", timeout=10):
   1931         dialog = c.see(r"(?i)Your Mailbox Address", timeout=15)
   1932         c.note("the address dialog: "
   1933                + (str(dialog.texts()[:8]) if dialog else "did not open"))
   1934         if dialog is not None:
   1935             address = next((t for t in dialog.texts()
   1936                             if "/" in t and "mailbox" in t.lower()), None)
   1937             c.note(f"the address it shows: {address}")
   1938             # The confirm button copies it to the clipboard and says so in a
   1939             # snackbar.  Polled tightly on purpose: `c.see` took long enough
   1940             # over its first dump to miss it, and reported "no confirmation"
   1941             # for a message that a probe found 0.4 s after the tap.
   1942             # tap_exact, not tap: on a dialog's text buttons the ancestor
   1943             # hunt lands somewhere that dismisses the dialog instead.
   1944             if c.tap_exact(r"(?i)^Copy$", timeout=8):
   1945                 snack = None
   1946                 for _ in range(10):
   1947                     dump = c.dev.dump()
   1948                     if dump.find(r"(?i)copied to clipboard") is not None:
   1949                         snack = dump
   1950                         break
   1951                     time.sleep(0.4)
   1952                 c.note("after copying: "
   1953                        + (str([t for t in snack.texts() if "clipboard" in t.lower()])
   1954                           if snack else "no confirmation seen"))
   1955         c.check()
   1956     else:
   1957         c.note("no address action; the mailbox has not registered: "
   1958                + str(c.dev.dump().texts()[:12]))
   1959 
   1960     # The URL dialog is always there, and cancelling it must change nothing.
   1961     if c.tap(r"(?i)^Configure Mailbox$", timeout=10):
   1962         dialog = c.see(r"(?i)Configure Mailbox URL|Mailbox Base URL", timeout=15)
   1963         c.note("the URL dialog: "
   1964                + (str(dialog.texts()[:8]) if dialog else "did not open"))
   1965         if dialog is not None:
   1966             c.fill("https://mailbox.example.org", 0, clear=True)
   1967             c.note("after typing a URL: " + str(c.dev.dump().texts()[:10]))
   1968             c.must_tap(r"(?i)^Cancel$", timeout=10)
   1969             time.sleep(1.5)
   1970             c.note("after cancelling: " + str(c.dev.dump().texts()[:12]))
   1971         c.check()
   1972 
   1973     if c.tap(r"(?i)^Refresh$", timeout=8):
   1974         time.sleep(3)
   1975         c.note("after refreshing: " + str(c.dev.dump().texts()[:12]))
   1976         c.check()
   1977     c.ep.check_database()
   1978 
   1979 
   1980 @scenario("forward_payment_to_contact", setup="funded",
   1981           about="forward a peer-push URI to a contact through the mailbox",
   1982           expects=("error-screen", "internal-error-code", "core-internal"))
   1983 def s_forward_payment_to_contact(c: Ctx) -> None:
   1984     """The app's sending side of the mailbox, which looks unreachable.
   1985 
   1986     `sendTalerUriMailboxMessage` hangs off a button that only exists in
   1987     developer mode, only on a pay-push/pay-pull QR screen, and is labelled
   1988     "Contacts" rather than anything about sending
   1989     (`compose/QrCodeUriComposable.kt:183`).  Tapping it opens the contacts
   1990     screen as "Send to Contact"; confirming a contact there is the call.
   1991 
   1992     The contact is the wallet's own mailbox address, so the message has
   1993     somewhere real to go and comes back to the sender -- which also checks that
   1994     a wallet can read what it sent itself.
   1995     """
   1996     # The wallet's own address, which it registers on first use against the
   1997     # default mailbox (now answered locally through the TLS front end).
   1998     open_mailbox(c)
   1999     if not c.tap(r"(?i)^Show Mailbox Address$", timeout=20):
   2000         c.note("no address dialog; the mailbox did not register: "
   2001                + str(c.dev.dump().texts()[:12]))
   2002         return
   2003     dialog = c.require(r"(?i)Your Mailbox Address", timeout=15)
   2004     address = next((t for t in dialog.texts()
   2005                     if "mailbox" in t.lower() and "/" in t), None)
   2006     c.note(f"the wallet's own mailbox address: {address}")
   2007     c.tap(r"(?i)^Cancel$|^OK$", timeout=8)
   2008     if not address:
   2009         return
   2010     c.check()
   2011 
   2012     # A peer-push payment, which is what the forward button appears on.
   2013     c.back_to_home()
   2014     c.must_tap(r"(?i)^Send$", timeout=30)
   2015     c.require(r"(?i)Send money|Amount to send|Purpose", timeout=30)
   2016     c.set_amount("€5.00", "500")
   2017     c.must_tap(r"(?i)^Send ", timeout=30)
   2018     if not c.see(r"(?i)Scan this QR code to receive|copy and send this URI",
   2019                  timeout=60):
   2020         c.note("the push never reached its QR screen: "
   2021                + str(c.dev.dump().texts()[:14]))
   2022         return
   2023     c.check()
   2024 
   2025     # "Contacts" here means "forward this payment to one".
   2026     if not c.tap_button(r"(?i)^Contacts$", timeout=20):
   2027         c.note("no forward button on the push screen (developer mode off?): "
   2028                + str(c.dev.dump().texts()[:14]))
   2029         return
   2030     picker = c.require(r"(?i)Send to Contact|No contacts yet|Add Contact",
   2031                        timeout=20)
   2032     c.note("the picker: " + str(picker.texts()[:12]))
   2033     c.check()
   2034 
   2035     # Add the wallet itself as a contact, if it is not already one.
   2036     if picker.find(r"(?i)^self$") is None:
   2037         if not c.tap(r"(?i)^Add Contact$", timeout=15):
   2038             c.note("no way to add a contact from the picker")
   2039             return
   2040         c.require(r"(?i)Petname|Alias Type", timeout=15)
   2041         fields = c.dev.dump().editable()
   2042         # petname, alias, (alias type is a read-only dropdown), mailbox
   2043         c.fill("self", 0, clear=True)
   2044         c.fill(f"self-w{WORKER}@example.com", 1, clear=True)
   2045         if len(fields) >= 4:
   2046             c.fill(address, len(fields) - 1, clear=True)
   2047         else:
   2048             c.note(f"the add-contact form has {len(fields)} fields, not 4")
   2049         c.tap_button(r"(?i)^OK$|^Add$|^Save$", timeout=10)
   2050         time.sleep(3)
   2051         c.note("after adding the contact: " + str(c.dev.dump().texts()[:12]))
   2052         c.check()
   2053 
   2054     if not c.tap(r"(?i)^self$", timeout=15):
   2055         c.note("the contact is not in the list: "
   2056                + str(c.dev.dump().texts()[:14]))
   2057         return
   2058     if c.see(r"(?i)Are you sure you want to send", timeout=15):
   2059         c.tap_button(r"(?i)^OK$", timeout=10)
   2060     time.sleep(8)
   2061     c.note("after sending: " + str(c.dev.dump().texts()[:14]))
   2062     c.check()
   2063 
   2064     # The message should arrive back in this very wallet.
   2065     open_mailbox(c)
   2066     for _ in range(8):
   2067         time.sleep(5)
   2068         c.tap(r"(?i)^Refresh$", timeout=5)
   2069         inbox = c.dev.dump()
   2070         if inbox.find(r"(?i)Accept payment|Pay invoice|From:") is not None:
   2071             c.note("the forwarded payment came back: " + str(inbox.texts()[:14]))
   2072             break
   2073     else:
   2074         c.note("the forwarded message did not arrive within 40s: "
   2075                + str(c.dev.dump().texts()[:14]))
   2076     c.check()
   2077     c.ep.check_database()
   2078 
   2079 
   2080 @scenario("mailbox_roundtrip", setup="funded",
   2081           about="register with a real mailbox service, receive and delete a message",
   2082           expects=("error-screen", "internal-error-code", "core-internal"))
   2083 def s_mailbox_roundtrip(c: Ctx) -> None:
   2084     """The mailbox screen against a deployed taler-mailbox.
   2085 
   2086     Its URL is the one service address the app lets the user type in, so no
   2087     DNS or TLS games are needed: point it at the local service, let the wallet
   2088     register itself, deliver a message to its address the way another wallet
   2089     would, and read and delete it.
   2090     """
   2091     url = service_or_skip(c, LOCAL_MAILBOX, "mailbox")
   2092     if url is None:
   2093         return
   2094     open_mailbox(c)
   2095     c.check()
   2096     # "Configure Mailbox" is an icon; its content description is the only name.
   2097     if not c.tap(r"(?i)^Configure Mailbox$", timeout=15):
   2098         c.note("no way to configure the mailbox URL: "
   2099                + str(c.dev.dump().texts()[:12]))
   2100         return
   2101     screen = c.require(r"(?i)Configure Mailbox URL|Mailbox Base URL", timeout=15)
   2102     if not screen.editable():
   2103         c.note("no URL field in the dialog")
   2104         return
   2105     # The field comes pre-filled with the production URL.
   2106     if not c.fill(url.rstrip("/"), 0, clear=True):
   2107         c.note("could not type the mailbox URL")
   2108         return
   2109     c.tap_button(r"(?i)^OK$", timeout=10)
   2110     time.sleep(6)
   2111     c.note("after configuring: " + str(c.dev.dump().texts()[:14]))
   2112     c.check()
   2113     # The wallet registers itself on first use; its address is behind the info
   2114     # icon.
   2115     if not c.tap(r"(?i)^Show Mailbox Address$", timeout=15):
   2116         c.note("no address dialog; the mailbox may not have registered")
   2117         return
   2118     dialog = c.require(r"(?i)Your Mailbox Address", timeout=15)
   2119     address = next((t for t in dialog.texts() if "localhost:11000" in t), None)
   2120     c.note(f"the wallet's mailbox address: {address}")
   2121     c.tap(r"(?i)^Cancel$", timeout=8)
   2122     if not address:
   2123         c.note("WARNING: the address dialog showed no address")
   2124         return
   2125     h_address = address.rstrip("/").rsplit("/", 1)[-1]
   2126     c.check()
   2127 
   2128     # Deliver a real message: the CLI wallet encrypts a taler:// URI for this
   2129     # address, which is what another wallet would do.  (The app itself has no
   2130     # caller for sendTalerUriMailboxMessage, so it can only receive.)
   2131     # Two messages, differing only in the scheme of the URI they carry: the
   2132     # row offers "Accept payment" only for a literal taler:// prefix, so the
   2133     # developer-mode scheme the rest of the app accepts everywhere else falls
   2134     # through to a bare string.
   2135     for scheme in ("taler://", "taler+http://"):
   2136         try:
   2137             sent = c.cli.send_mailbox_message(
   2138                 h_address.upper(),
   2139                 f"{scheme}pay-push/localhost:8081/" + "A" * 52,
   2140                 mailbox_base=url.replace("localhost", "127.0.0.1"))
   2141             c.note(f"another wallet sent a {scheme} message: {str(sent)[:120]}")
   2142         except Exception as e:  # noqa: BLE001
   2143             c.note(f"the peer wallet could not send {scheme}: {str(e)[:160]}")
   2144         time.sleep(2)
   2145     c.tap(r"(?i)^Refresh$", timeout=10)
   2146     time.sleep(8)
   2147     listed = c.dev.dump()
   2148     c.note("after two real messages: " + str(listed.texts()[:20]))
   2149     if listed.find(r"(?i)No messages yet") is not None:
   2150         c.note("WARNING: a message another wallet sent does not appear")
   2151     actions = [t for t in listed.texts()
   2152                if t.strip() in ("Accept payment", "Pay invoice")]
   2153     raw = [t for t in listed.texts() if t.startswith(("taler://", "taler+http://"))]
   2154     c.note(f"rows offering an action: {len(actions)}; rows showing a raw URI: {raw}")
   2155     if raw:
   2156         c.note("WARNING: a received payment with no way to accept it")
   2157     c.check()
   2158 
   2159     # And one the wallet cannot read: anyone may POST to a mailbox address, so
   2160     # what the app does with junk is worth knowing.  It turns out to fetch it,
   2161     # fail to make sense of it, delete it from the server and say nothing --
   2162     # which is the right instinct for a public drop box.
   2163     import urllib.request
   2164     # The service insists on exactly message_body_bytes, so ask it how long a
   2165     # message is rather than guessing (43 bytes earns a flat 400).
   2166     size = 256
   2167     try:
   2168         with urllib.request.urlopen(url + "config", timeout=5) as r:
   2169             size = int(json.loads(r.read()).get("message_body_bytes", 256))
   2170     except Exception as e:  # noqa: BLE001
   2171         c.note(f"could not read the mailbox config: {str(e)[:80]}")
   2172     c.note(f"a message is {size} bytes here")
   2173     # Not a valid envelope: what the app does with a message it cannot make
   2174     # sense of is worth knowing too.
   2175     body = (b"simulator test message, not a valid envelope. "
   2176             * (size // 46 + 1))[:size]
   2177     req = urllib.request.Request(url + h_address.upper(), data=body,
   2178                                  method="POST")
   2179     try:
   2180         with urllib.request.urlopen(req, timeout=10) as r:
   2181             c.note(f"delivered a message: HTTP {r.status}")
   2182     except Exception as e:  # noqa: BLE001
   2183         c.note(f"could not deliver a message: {str(e)[:160]}")
   2184     time.sleep(2)
   2185     c.tap(r"(?i)^Refresh$", timeout=10)
   2186     time.sleep(6)
   2187     after = c.dev.dump()
   2188     c.note("after refreshing: " + str(after.texts()[:16]))
   2189     c.check()
   2190     # A message row offers a delete button; that is the only path to
   2191     # deleteMailboxMessage.
   2192     if c.tap(r"(?i)^Delete$|delete message", timeout=10):
   2193         time.sleep(3)
   2194         c.note("after deleting: " + str(c.dev.dump().texts()[:14]))
   2195         c.check()
   2196     c.ep.check_database()
   2197 
   2198 
   2199 @scenario("contacts_list", setup="funded", about="the contacts screen from settings")
   2200 def s_contacts_list(c: Ctx) -> None:
   2201     c.app.open_settings()
   2202     c.app.scroll_to_text(r"(?i)^Contacts$", max_scrolls=10)
   2203     c.must_tap(r"(?i)^Contacts$")
   2204     c.require(r"(?i)contact|alias|empty", timeout=25)
   2205     c.note("contacts: " + str(c.dev.dump().texts()[:14]))
   2206     c.check()
   2207     c.tap(r"(?i)^Add$|^New$|Add contact", timeout=8)
   2208     c.check()
   2209 
   2210 
   2211 @scenario("uri_add_contact", setup="funded", about="a taler://add-contact/ URI")
   2212 def s_uri_add_contact(c: Ctx) -> None:
   2213     for uri in (f"taler+http://add-contact/{corpus.EXCHANGE}/{corpus.FAKE_ID}",
   2214                 "taler+http://add-contact/"):
   2215         c.app.handle_uri(uri)
   2216         time.sleep(2.5)
   2217         c.note(f"{uri[:48]}: {c.dev.dump().texts()[:8]}")
   2218         c.check()
   2219         c.back_to_home()
   2220 
   2221 
   2222 @scenario("uri_dev_experiment", setup="funded", about="a taler://dev-experiment/ URI")
   2223 def s_uri_dev_experiment(c: Ctx) -> None:
   2224     for uri in ("taler+http://dev-experiment/nonexistent",
   2225                 "taler+http://dev-experiment/",
   2226                 "taler+http://dev-experiment/" + "x" * 300):
   2227         c.app.handle_uri(uri)
   2228         time.sleep(2.5)
   2229         c.note(f"{uri[:42]}: {c.dev.dump().texts()[:8]}")
   2230         c.check()
   2231         c.back_to_home()
   2232 
   2233 
   2234 @scenario("payment_insufficient_reason", setup="funded",
   2235           about="a payment refused for a named reason, not just 'insufficient'",
   2236           expects=("error-screen", "internal-error-code", "core-internal"))
   2237 def s_payment_insufficient_reason(c: Ctx) -> None:
   2238     """The typed half of `PaymentResponses.kt`.
   2239 
   2240     `payment_insufficient` reaches the plain "not enough money" case.  The
   2241     insufficient-balance *details* -- `PaymentInsufficientBalanceDetails`,
   2242     `PerExchange`, and the mapping from each reason to its own hint string at
   2243     `PaymentResponses.kt:186` -- need a refusal with a reason attached, and the
   2244     wallet cannot manufacture one.  wallet-core can: the
   2245     `merchant-deposit-insufficient` dev experiment
   2246     (`dev-experiments.ts:269`) makes the next payment fail as though the
   2247     merchant's account could not take the deposit.
   2248     """
   2249     c.app.handle_uri("taler+http://dev-experiment/merchant-deposit-insufficient")
   2250     time.sleep(3)
   2251     c.note("after arming the experiment: " + str(c.dev.dump().texts()[:10]))
   2252     c.back_to_home()
   2253     c.check()
   2254 
   2255     # A neutral summary on purpose: the first version called the order
   2256     # "Order the merchant cannot take", and every pattern below then matched
   2257     # the summary instead of the wallet's own text.
   2258     order = c.merchant.create_order("EUR:1", summary="Simulator order")
   2259     c.app.handle_uri(order["pay_uri"])
   2260     screen = c.require(r"(?i)Review order|Total|^Pay\b|Insufficient balance",
   2261                        timeout=60)
   2262     c.note("the prompt: " + str(screen.texts()[:16]))
   2263     c.check()
   2264     # "Insufficient balance" is the state; the hint beside it is the reason,
   2265     # and the reason is what PaymentResponses.kt:186 maps.
   2266     state = screen.find(r"(?i)^Insufficient balance$")
   2267     if state is None and c.tap_button(r"(?i)^Pay\b", timeout=20):
   2268         time.sleep(6)
   2269         screen = c.dev.dump()
   2270         c.note("after confirming: " + str(screen.texts()[:16]))
   2271         state = screen.find(r"(?i)^Insufficient balance$")
   2272     c.note(f"the wallet says the balance is insufficient: {state is not None}")
   2273     # One of the seven hint strings, matched on wording the order summary
   2274     # cannot contain.
   2275     hint = screen.find(
   2276         r"(?i)wire method of the payment service"
   2277         r"|doesn't accept money from one or more"
   2278         r"|due to age restriction"
   2279         r"|missing the global fee configuration"
   2280         r"|fees not covered by the merchant"
   2281         r"|coins needed for this purchase are currently unavailable")
   2282     c.note(f"a reason-specific hint: {hint is not None}"
   2283            + (f" -- {hint.label[:140]}" if hint is not None else ""))
   2284     if state is not None and hint is None:
   2285         c.note("WARNING: insufficient balance with no reason shown, though "
   2286                "the experiment armed a specific one")
   2287     c.check()
   2288     c.ep.check_database()
   2289 
   2290 
   2291 @scenario("payment_template", setup="funded", about="pay through an order template")
   2292 def s_payment_template(c: Ctx) -> None:
   2293     c.merchant.create_template("simtemplate", "EUR:1")
   2294     uri = (f"taler+http://pay-template/localhost:8080/instances/"
   2295            f"{c.merchant.instance}/simtemplate")
   2296     c.app.handle_uri(uri)
   2297     screen = c.see(r"(?i)amount|summary|Pay|Order|template", timeout=40)
   2298     c.note("template prompt: " + str(screen.texts()[:12] if screen else None))
   2299     c.check()
   2300     # Templates can ask for the amount and the subject.
   2301     if screen and screen.editable():
   2302         c.fill("1")
   2303     c.tap(r"(?i)^Pay|^Continue$|^Next$|^Order$", timeout=20)
   2304     time.sleep(4)
   2305     c.note("after template pay: " + str(c.dev.dump().texts()[:10]))
   2306     c.check()
   2307 
   2308 
   2309 @scenario("payment_expired", setup="funded", about="pay an order whose deadline has passed")
   2310 def s_payment_expired(c: Ctx) -> None:
   2311     import time as _t
   2312     deadline = int(_t.time()) + 5
   2313     order = c.merchant.create_order(
   2314         "EUR:1", summary="Order that expires at once",
   2315         pay_deadline={"t_s": deadline},
   2316     )
   2317     _t.sleep(10)
   2318     c.app.handle_uri(order["pay_uri"])
   2319     time.sleep(3)
   2320     c.note("expired order: " + str(c.dev.dump().texts()[:12]))
   2321     c.check()
   2322 
   2323 
   2324 @scenario("payment_deleted_order", setup="funded",
   2325           about="pay an order the merchant deleted in the meantime")
   2326 def s_payment_deleted(c: Ctx) -> None:
   2327     order = c.merchant.create_order("EUR:1", summary="Order about to vanish")
   2328     try:
   2329         c.merchant.delete_order(order["order_id"])
   2330         c.note("merchant deleted the order")
   2331     except Exception as e:
   2332         c.note(f"merchant refused to delete the order: {e}")
   2333     c.app.handle_uri(order["pay_uri"])
   2334     time.sleep(3)
   2335     c.note("after paying a deleted order: " + str(c.dev.dump().texts()[:12]))
   2336     c.check()
   2337 
   2338 
   2339 @scenario("refresh_history", setup="paid",
   2340           about="the refresh transaction left behind by paying")
   2341 def s_refresh_history(c: Ctx) -> None:
   2342     screen = open_transactions(c)
   2343     rows = transaction_rows(screen)
   2344     c.note(f"rows: {[n.label[:24] for n in rows]}")
   2345     # Change ("refresh") transactions appear after spending part of a coin.
   2346     for index, node in enumerate(rows):
   2347         screen = open_transactions(c)
   2348         rows_now = transaction_rows(screen)
   2349         if index >= len(rows_now):
   2350             break
   2351         c.dev.tap_node(rows_now[index], screen)
   2352         time.sleep(2)
   2353         detail = c.dev.dump()
   2354         if detail.find(r"(?i)change|refresh"):
   2355             c.note(f"change transaction detail: {detail.texts()[:10]}")
   2356             c.check()
   2357         c.dev.back()
   2358         time.sleep(1)
   2359     c.check()
   2360 
   2361 
   2362 @scenario("lifecycle_kill", setup="fresh",
   2363           about="suspend, kill the app, relaunch, resume: does the state survive?")
   2364 def s_lifecycle_kill(c: Ctx) -> None:
   2365     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
   2366     c.app.handle_uri(op["taler_withdraw_uri"])
   2367     c.accept_tos()
   2368     c.must_tap(r"(?i)confirm withdrawal", timeout=60)
   2369     c.see(r"(?i)Waiting for authorization|Authorize in bank", timeout=60)
   2370     c.must_tap(r"(?i)^Suspend$")
   2371     time.sleep(2)
   2372     suspended = c.dev.dump().texts()
   2373     c.note(f"suspended: {suspended[:8]}")
   2374     # Process death without a clean shutdown, the way the system would do it.
   2375     c.dev.kill()
   2376     time.sleep(2)
   2377     c.dev.launch()
   2378     time.sleep(6)
   2379     c.check()
   2380     screen = open_transactions(c)
   2381     rows = transaction_rows(screen)
   2382     c.note(f"after relaunch, {len(rows)} rows: {[n.label[:24] for n in rows]}")
   2383     if rows:
   2384         c.dev.tap_node(rows[0], screen)
   2385         time.sleep(2)
   2386         detail = c.dev.dump()
   2387         c.note(f"detail after relaunch: {detail.texts()[:10]}")
   2388         # A suspended transaction must still offer Resume.
   2389         if detail.find(r"(?i)^Resume$") is None:
   2390             c.note("WARNING: no Resume on a suspended transaction after process death")
   2391         c.tap(r"(?i)^Resume$", timeout=15)
   2392         time.sleep(3)
   2393     c.check()
   2394     c.ep.check_database()
   2395 
   2396 
   2397 @scenario("abort_then_retry", setup="fresh",
   2398           about="abort a withdrawal, then hand the same URI in again")
   2399 def s_abort_then_retry(c: Ctx) -> None:
   2400     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
   2401     uri = op["taler_withdraw_uri"]
   2402     c.app.handle_uri(uri)
   2403     c.accept_tos()
   2404     c.must_tap(r"(?i)confirm withdrawal", timeout=60)
   2405     c.see(r"(?i)Waiting for authorization|Authorize in bank", timeout=60)
   2406     c.must_tap(r"(?i)^Abort$")
   2407     if c.see(r"(?i)Abort transaction|Are you sure", timeout=10):
   2408         c.tap(r"(?i)^Abort$|^OK$|^Yes$")
   2409     time.sleep(3)
   2410     c.check()
   2411     # The same URI again: the operation is dead at the bank, so the wallet has
   2412     # to say so rather than start over.
   2413     c.app.handle_uri(uri)
   2414     time.sleep(4)
   2415     c.note("re-handled an aborted withdraw URI: " + str(c.dev.dump().texts()[:12]))
   2416     c.check()
   2417     c.ep.check_database()
   2418 
   2419 
   2420 @scenario("amount_edges_deposit", setup="funded",
   2421           about="hostile amounts in the deposit amount field")
   2422 def s_amount_edges_deposit(c: Ctx) -> None:
   2423     values = ["0", "0.00", "-1", "999999999", "1.999", "0.001", "1e5", "abc", "9.87"]
   2424     for value in values:
   2425         c.back_to_home()
   2426         if not c.tap(r"(?i)^Deposit$", timeout=20):
   2427             c.note("no Deposit button on the balance card")
   2428             return
   2429         screen = c.see(r"(?i)deposit to bank account|x-taler-bank|Amount to deposit",
   2430                        timeout=20)
   2431         if screen is not None and screen.find(r"(?i)Amount to deposit") is None:
   2432             # Pick a target account to reach the amount field.
   2433             account = (screen.find(r"(?i)^wallet\d+$")
   2434                        or screen.find(r"(?i)x-taler-bank"))
   2435             if account is not None:
   2436                 c.dev.tap_node(account, screen)
   2437                 time.sleep(2)
   2438         if not c.fill(value):
   2439             c.note(f"no amount field for {value!r}")
   2440             c.dev.back()
   2441             continue
   2442         time.sleep(1)
   2443         screen = c.dev.dump()
   2444         c.note(f"{value!r}: {[t for t in screen.texts() if 'nvalid' in t or 'xceed' in t or 'rror' in t][:3]}")
   2445         # Try to proceed; a bad amount must not get past the form.
   2446         c.tap(r"(?i)^Make deposit$|^Check fees$|^Deposit$|^Next$", timeout=8)
   2447         time.sleep(1.5)
   2448         c.check()
   2449         c.back_to_home()
   2450     c.ep.check_database()
   2451 
   2452 
   2453 @scenario("amount_edges_peer", setup="funded",
   2454           about="hostile amounts in the peer send amount field")
   2455 def s_amount_edges_peer(c: Ctx) -> None:
   2456     values = ["0", "-5", "100000", "1.999", "0.001", "9.87", "1,5"]
   2457     for value in values:
   2458         c.back_to_home()
   2459         if not c.tap(r"(?i)^Send$", timeout=20):
   2460             c.note("no Send button on the balance card")
   2461             return
   2462         c.see(r"(?i)Amount to send|Purpose|Send money", timeout=20)
   2463         if not c.fill(value):
   2464             c.note(f"no amount field for {value!r}")
   2465             c.dev.back()
   2466             continue
   2467         time.sleep(1)
   2468         screen = c.dev.dump()
   2469         c.note(f"{value!r}: {[t for t in screen.texts() if 'nvalid' in t or 'xceed' in t or 'rror' in t][:3]}")
   2470         c.tap(r"(?i)^Send ", timeout=8)
   2471         time.sleep(1.5)
   2472         c.check()
   2473         c.back_to_home()
   2474     c.ep.check_database()
   2475 
   2476 
   2477 @scenario("offline_withdraw", setup="fresh",
   2478           about="lose the network in the middle of a withdrawal, then get it back")
   2479 def s_offline_withdraw(c: Ctx) -> None:
   2480     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
   2481     c.app.handle_uri(op["taler_withdraw_uri"])
   2482     c.accept_tos()
   2483     c.must_tap(r"(?i)confirm withdrawal", timeout=60)
   2484     c.see(r"(?i)Waiting for authorization|Authorize in bank", timeout=60)
   2485     # Airplane mode: the emulator keeps the adb connection, so the driver can
   2486     # still watch what the app does without a network.
   2487     c.dev.shell("cmd connectivity airplane-mode enable", check=False)
   2488     time.sleep(3)
   2489     c.bank.confirm_withdrawal(*flows.WALLET_USER, op["withdrawal_id"])
   2490     time.sleep(6)
   2491     c.note("offline: " + str(c.dev.dump().texts()[:10]))
   2492     c.check()
   2493     c.tap(r"(?i)^Retry$", timeout=10)
   2494     time.sleep(3)
   2495     c.check()
   2496     c.dev.shell("cmd connectivity airplane-mode disable", check=False)
   2497     time.sleep(8)
   2498     # Once the network is back the withdrawal should finish on its own.
   2499     done = False
   2500     for _ in range(12):
   2501         if c.dev.dump().find(r"(?i)completed successfully"):
   2502             done = True
   2503             break
   2504         c.tap(r"(?i)^Retry$", timeout=4)
   2505         time.sleep(5)
   2506     c.note(f"recovered after reconnect: {done}")
   2507     if not done:
   2508         c.note("WARNING: withdrawal did not complete after the network came back")
   2509     c.check()
   2510     c.ep.check_database()
   2511 
   2512 
   2513 @scenario("concurrent_uris", setup="funded", about="two pay URIs delivered back to back")
   2514 def s_concurrent_uris(c: Ctx) -> None:
   2515     first = c.merchant.create_order("EUR:1", summary="First of two")
   2516     second = c.merchant.create_order("EUR:1", summary="Second of two")
   2517     c.dev.send_uri(first["pay_uri"])
   2518     time.sleep(0.8)
   2519     c.dev.send_uri(second["pay_uri"])
   2520     time.sleep(4)
   2521     screen = c.dev.dump()
   2522     c.note("after two URIs: " + str(screen.texts()[:12]))
   2523     c.check()
   2524     c.tap(r"(?i)^Pay", timeout=20)
   2525     time.sleep(4)
   2526     for order in (first, second):
   2527         status = c.merchant.order_status(order["order_id"], order["token"])
   2528         c.note(f"{order['order_id']}: {status.get('order_status')}")
   2529     c.check()
   2530     c.ep.check_database()
   2531 
   2532 
   2533 @scenario("exchange_delete_with_coins", setup="funded",
   2534           about="delete (and purge) an exchange the wallet holds coins at")
   2535 def s_exchange_delete_with_coins(c: Ctx) -> None:
   2536     open_exchange_list(c)
   2537     if not exchange_menu(c):
   2538         raise RuntimeError(f"no exchange menu; screen: {c.dev.dump().texts()}")
   2539     c.must_tap(r"(?i)^Delete payment service$")
   2540     screen = c.see(r"(?i)Force deletion|Are you sure|purge|Delete", timeout=20)
   2541     c.note("delete dialog: " + str(screen.texts()[:10] if screen else None))
   2542     c.check()
   2543     # Refusing to delete while coins remain is correct; forcing it is the
   2544     # interesting path.
   2545     c.tap(r"(?i)Force deletion", timeout=10)
   2546     c.tap(r"(?i)^Delete$|^OK$|^Yes$", timeout=10)
   2547     time.sleep(4)
   2548     c.note("after forced deletion: " + str(c.dev.dump().texts()[:12]))
   2549     c.check()
   2550     c.back_to_home()
   2551     c.note("home after purge: " + str(c.dev.dump().texts()[:12]))
   2552     c.check()
   2553     c.ep.check_database()
   2554 
   2555 
   2556 @scenario("tos_reject_midflow", setup="fresh",
   2557           about="reject the terms of service while a withdrawal is pending")
   2558 def s_tos_reject_midflow(c: Ctx) -> None:
   2559     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
   2560     c.app.handle_uri(op["taler_withdraw_uri"])
   2561     c.accept_tos()
   2562     c.must_tap(r"(?i)confirm withdrawal", timeout=60)
   2563     c.see(r"(?i)Waiting for authorization|Authorize in bank", timeout=60)
   2564     open_exchange_list(c)
   2565     if exchange_menu(c):
   2566         if c.tap(r"(?i)^Reject terms of service$"):
   2567             time.sleep(3)
   2568             c.note("rejected the terms of service mid-withdrawal")
   2569             c.check()
   2570     c.bank.confirm_withdrawal(*flows.WALLET_USER, op["withdrawal_id"])
   2571     time.sleep(8)
   2572     c.back_to_home()
   2573     c.note("after the bank confirmed: " + str(c.dev.dump().texts()[:12]))
   2574     c.check()
   2575     c.ep.check_database()
   2576 
   2577 
   2578 @scenario("tokens_issue_and_view", setup="funded",
   2579           about="pay a v1 order that issues a discount token, then view it")
   2580 def s_tokens_issue(c: Ctx) -> None:
   2581     c.merchant.create_token_family("simdiscount", "discount")
   2582     order = c.merchant.create_v1_order(
   2583         [{"amount": "EUR:1", "description": "Buy one, get a discount token",
   2584           "inputs": [], "outputs": [c.merchant.token_output("simdiscount")],
   2585           "max_fee": "EUR:0.5"}],
   2586         summary="Issues a discount token",
   2587     )
   2588     c.app.handle_uri(order["pay_uri"])
   2589     screen = c.require(r"(?i)Review order|Total:|^Pay", timeout=60)
   2590     c.note("v1 prompt: " + str(screen.texts()[:14]))
   2591     c.check()
   2592     c.must_tap(r"(?i)^Pay\b|confirm payment", timeout=40)
   2593     paid = False
   2594     for _ in range(20):
   2595         if c.merchant.order_status(order["order_id"],
   2596                                    order["token"]).get("order_status") == "paid":
   2597             paid = True
   2598             break
   2599         time.sleep(2)
   2600     c.note(f"order paid: {paid}")
   2601     # The issued token should now show up under Discounts.
   2602     c.back_to_home()
   2603     try:
   2604         c.app.scroll_to_text(r"(?i)^Discounts$", max_scrolls=5)
   2605     except TimeoutError:
   2606         c.note("no Discounts section on the main screen")
   2607         c.check()
   2608         return
   2609     c.must_tap(r"(?i)^Discounts$")
   2610     screen = c.require(r"(?i)discount|available|expired|empty", timeout=25)
   2611     c.note("discounts screen: " + str(screen.texts()[:14]))
   2612     for tab in (r"(?i)^Available$", r"(?i)^Expired$"):
   2613         c.tap(tab, timeout=8)
   2614         c.check()
   2615     c.check()
   2616     c.ep.check_database()
   2617 
   2618 
   2619 # An 8x8 red PNG, which is enough for the wallet to decode and draw.  The
   2620 # wallet accepts exactly `data:image/(jpeg|png);base64,<b64>`
   2621 # (AndroidUtils.kt:278), so the prefix matters.
   2622 PRODUCT_IMAGE = (
   2623     "data:image/png;base64,"
   2624     "iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAIAAABLbSncAAAAEUlEQVR4nGM4ISeHFTEMLQkA"
   2625     "kL9BAbKfPiIAAAAASUVORK5CYII="
   2626 )
   2627 
   2628 
   2629 @scenario("payment_product_image", setup="funded",
   2630           about="an order whose product carries an image, and the image dialog")
   2631 def s_payment_product_image(c: Ctx) -> None:
   2632     """`ProductImageDialog` has exactly one caller: tapping a product's image
   2633     on the payment prompt.  No order any scenario made carried an image, so
   2634     neither the image nor the dialog had ever been drawn.
   2635     """
   2636     order = c.merchant.create_order(
   2637         "EUR:2", summary="Order with a pictured product",
   2638         products=[{"description": "A red square", "price": "EUR:2",
   2639                    "image": PRODUCT_IMAGE, "quantity": 1}],
   2640     )
   2641     c.app.handle_uri(order["pay_uri"])
   2642     screen = c.require(r"(?i)A red square|Review order|^Pay\b", timeout=60)
   2643     c.note("prompt with a product: " + str(screen.texts()[:14]))
   2644     if screen.find(r"(?i)A red square") is None:
   2645         c.note("WARNING: the product is not on the prompt at all")
   2646     c.check()
   2647 
   2648     # The image carries no content description (PromptPaymentComposable.kt:372
   2649     # passes null), so it can only be found as an unnamed clickable -- which
   2650     # is also what a11y_audit would say about it, if any order it saw had an
   2651     # image.
   2652     unnamed = screen.unnamed_clickables()
   2653     c.note(f"{len(unnamed)} unnamed clickable(s): "
   2654            + str([n.bounds for n in unnamed][:6]))
   2655     if not unnamed:
   2656         c.note("no unnamed clickable, so the image did not render")
   2657         c.check()
   2658         return
   2659     target = min(unnamed, key=lambda n: n.area)
   2660     c.dev.tap(*target.center)
   2661     time.sleep(2)
   2662     after = c.dev.dump()
   2663     c.note("after tapping the image: " + str(after.texts()[:12]))
   2664     # The dialog is its own window with no text in it, so what says it opened
   2665     # is that the prompt behind it is no longer in the dump.
   2666     if after.find(r"(?i)^Pay\b|Review order") is None:
   2667         c.note("the image dialog is up: the prompt is no longer dumped")
   2668         c.check()
   2669         # It dismisses by being tapped.
   2670         c.dev.tap(*target.center)
   2671         time.sleep(2)
   2672         back = c.dev.dump()
   2673         c.note("after dismissing: " + str(back.texts()[:12]))
   2674         if back.find(r"(?i)^Pay\b|Review order") is None:
   2675             c.note("WARNING: the prompt did not come back")
   2676     else:
   2677         c.note("tapping the smallest unnamed clickable changed nothing; "
   2678                "the image may be elsewhere in the row")
   2679     c.check()
   2680     # Leave nothing pending behind.
   2681     c.tap(r"(?i)^Cancel$|^Abort$", timeout=8)
   2682     c.ep.check_database()
   2683 
   2684 
   2685 @scenario("payment_choices", setup="funded",
   2686           about="a v1 order with several choices to pick from")
   2687 def s_payment_choices(c: Ctx) -> None:
   2688     c.merchant.create_token_family("simdiscount", "discount")
   2689     order = c.merchant.create_v1_order(
   2690         [
   2691             {"amount": "EUR:2", "description": "Full price", "inputs": [],
   2692              "outputs": [], "max_fee": "EUR:0.5"},
   2693             {"amount": "EUR:1", "description": "Discounted, needs a token",
   2694              "inputs": [c.merchant.token_input("simdiscount")], "outputs": [],
   2695              "max_fee": "EUR:0.5"},
   2696             {"amount": "EUR:3", "description": "Full price plus a token",
   2697              "inputs": [], "outputs": [c.merchant.token_output("simdiscount")],
   2698              "max_fee": "EUR:0.5"},
   2699         ],
   2700         summary="Three ways to pay",
   2701     )
   2702     c.app.handle_uri(order["pay_uri"])
   2703     screen = c.require(r"(?i)Review order|choice|Full price|Total:|^Pay", timeout=60)
   2704     c.note("choices prompt: " + str(screen.texts()[:18]))
   2705     c.check()
   2706     # Pick the choice that needs no token, then pay it.
   2707     c.tap(r"(?i)Full price$", timeout=15)
   2708     c.check()
   2709     c.tap(r"(?i)^Pay\b|confirm payment", timeout=30)
   2710     time.sleep(4)
   2711     status = c.merchant.order_status(order["order_id"], order["token"])
   2712     c.note(f"order status: {status.get('order_status')}")
   2713     c.check()
   2714     c.ep.check_database()
   2715 
   2716 
   2717 @scenario("subscription_issued_and_viewed", setup="funded",
   2718           about="buy a subscription token and open it under Passes")
   2719 def s_subscription_issued_and_viewed(c: Ctx) -> None:
   2720     """A subscription the wallet actually holds.
   2721 
   2722     `payment_needs_token` creates a subscription family and *demands* the
   2723     token, so the wallet never holds one and `PassList`'s rows never render --
   2724     the pass list item and `SubscriptionListDetail` are the uncovered half of
   2725     `TokenListScreen`.  This buys one instead: an order whose output is a
   2726     subscription token.
   2727     """
   2728     c.merchant.create_token_family("simsub", "subscription", "Simulator pass")
   2729     order = c.merchant.create_v1_order(
   2730         [{"amount": "EUR:2", "description": "A month of something",
   2731           "inputs": [], "outputs": [c.merchant.token_output("simsub")],
   2732           "max_fee": "EUR:0.5"}],
   2733         summary="Subscription purchase",
   2734     )
   2735     c.app.handle_uri(order["pay_uri"])
   2736     screen = c.require(r"(?i)Review order|Total:|^Pay\b|subscription", timeout=60)
   2737     c.note("subscription prompt: " + str(screen.texts()[:14]))
   2738     c.check()
   2739     c.must_tap(r"(?i)^Pay\b|confirm payment", timeout=30)
   2740     deadline = time.time() + 60
   2741     paid = False
   2742     while time.time() < deadline:
   2743         if c.merchant.order_status(order["order_id"],
   2744                                    order["token"]).get("order_status") == "paid":
   2745             paid = True
   2746             break
   2747         time.sleep(2)
   2748     c.note(f"the merchant says the order was paid: {paid}")
   2749     c.check()
   2750 
   2751     # "Passes" is the subscription view; "Discounts" is the other one.
   2752     c.back_to_home()
   2753     try:
   2754         c.app.scroll_to_text(r"(?i)^Passes$", max_scrolls=6)
   2755     except TimeoutError:
   2756         c.note("no Passes entry on the main screen: "
   2757                + str(c.dev.dump().texts()[:16]))
   2758         c.check()
   2759         c.ep.check_database()
   2760         return
   2761     c.must_tap(r"(?i)^Passes$", timeout=10)
   2762     time.sleep(2.5)
   2763     screen = c.dev.dump()
   2764     c.note("passes: " + str(screen.texts()[:16]))
   2765     # Not matched on the family's name: `create_token_family` returns 409 when
   2766     # the slug exists and leaves the old name in place, so "simsub" is called
   2767     # whatever the scenario that created it first called it.  What says a pass
   2768     # is listed is a row with a validity.
   2769     if screen.find(r"(?i)^Active$|Valid until") is None:
   2770         c.note("WARNING: the pass the wallet just bought is not listed")
   2771     c.check()
   2772     # Tapping a row opens its detail, which is its own composable.
   2773     rows = [n for n in screen.labelled()
   2774             if re.search(r"(?i)Valid until|^Active$|tokens issued", n.label)]
   2775     if rows:
   2776         c.dev.tap(*rows[0].center)
   2777         time.sleep(2)
   2778         c.note("pass detail: " + str(c.dev.dump().texts()[:14]))
   2779         c.check()
   2780     for tab in (r"(?i)^Available$", r"(?i)^Expired$"):
   2781         if c.tap(tab, timeout=6):
   2782             time.sleep(1.5)
   2783             c.note(f"{tab}: " + str(c.dev.dump().texts()[:10]))
   2784             c.check()
   2785     c.ep.check_database()
   2786 
   2787 
   2788 @scenario("payment_needs_token", setup="funded",
   2789           about="an order that can only be paid with a token the wallet lacks")
   2790 def s_payment_needs_token(c: Ctx) -> None:
   2791     c.merchant.create_token_family("simsub", "subscription")
   2792     order = c.merchant.create_v1_order(
   2793         [{"amount": "EUR:0", "description": "Subscribers only",
   2794           "inputs": [c.merchant.token_input("simsub")], "outputs": [],
   2795           "max_fee": "EUR:0.5"}],
   2796         summary="Requires a subscription token",
   2797     )
   2798     c.app.handle_uri(order["pay_uri"])
   2799     time.sleep(4)
   2800     screen = c.dev.dump()
   2801     c.note("prompt without the token: " + str(screen.texts()[:16]))
   2802     # The wallet should explain that it cannot satisfy the contract.
   2803     if screen.find(r"(?i)token|subscription|cannot|unavailable|missing|insufficient") is None:
   2804         c.note("WARNING: nothing on screen explains the missing token")
   2805     c.check()
   2806     c.ep.check_database()
   2807 
   2808 
   2809 @scenario("payment_pos_confirmation", setup="funded",
   2810           about="an order tied to a point-of-sale device shows its TOTP code")
   2811 def s_payment_pos_confirmation(c: Ctx) -> None:
   2812     """`PayTotpComposable` is only reachable through a pos_confirmation.
   2813 
   2814     The merchant puts one in the pay reply when the order names an OTP
   2815     device, and the wallet then renders the code (and an NDEF message) on the
   2816     payment's detail screen.
   2817     """
   2818     c.merchant.create_otp_device("simpos")
   2819     order = c.merchant.create_order("EUR:1", summary="Point of sale order",
   2820                                     otp_id="simpos")
   2821     c.app.handle_uri(order["pay_uri"])
   2822     c.app.dev.tap_text(r"(?i)^pay\b|confirm payment", timeout=60)
   2823     deadline = time.time() + 90
   2824     while time.time() < deadline:
   2825         if c.merchant.order_status(order["order_id"],
   2826                                    order["token"]).get("order_status") == "paid":
   2827             break
   2828         time.sleep(2)
   2829     else:
   2830         raise RuntimeError(f"order {order['order_id']} was not paid")
   2831     screen = c.require(r"(?i)Payment|Completed|paid", timeout=45)
   2832     c.note("after paying a pos order: " + str(screen.texts()[:16]))
   2833     # The merchant returns every T-OTP code in the valid time range, newline
   2834     # separated, and the wallet prints the lot in one Text node.
   2835     codes = [line.strip() for t in screen.texts() for line in t.splitlines()
   2836              if re.fullmatch(r"\d{6,}", line.strip())]
   2837     c.note(f"confirmation codes on the detail screen: {codes}")
   2838     if not codes:
   2839         c.note("WARNING: no pos_confirmation shown for an order with an OTP device")
   2840     elif len(codes) > 1:
   2841         c.note(f"WARNING: {len(codes)} codes shown under a singular label")
   2842     c.check()
   2843     # A TOTP code is valid for 30 s, and the composable has a timer that
   2844     # recomputes it -- so staying on the screen for one period is the only way
   2845     # to run that half of PayTotpComposable.
   2846     time.sleep(35)
   2847     later = c.dev.dump()
   2848     codes_later = [line.strip() for x in later.texts() for line in x.splitlines()
   2849                    if re.fullmatch(r"\d{6,}", line.strip())]
   2850     c.note(f"codes after one TOTP period: {codes_later}")
   2851     if codes and codes_later and codes == codes_later:
   2852         c.note("the codes did not change across a TOTP period")
   2853     c.check()
   2854     c.ep.check_database()
   2855 
   2856 
   2857 @scenario("a11y_audit", setup="paid",
   2858           about="walk the main screens and list clickable elements with no name")
   2859 def s_a11y_audit(c: Ctx) -> None:
   2860     """Every unnamed clickable node is a control a screen reader cannot announce.
   2861 
   2862     Layout containers show up too, so this records rather than judges; what
   2863     makes it useful is the per-screen count and the neighbouring labels, which
   2864     is how the Send/Request/Withdraw/Deposit defect was spotted.
   2865     """
   2866     visited: dict[str, int] = {}
   2867 
   2868     def audit(where: str) -> None:
   2869         screen = c.dev.dump()
   2870         unnamed = screen.unnamed_clickables()
   2871         visited[where] = len(unnamed)
   2872         if unnamed:
   2873             near = []
   2874             for node in unnamed[:6]:
   2875                 label = min(
   2876                     (n for n in screen.labelled()),
   2877                     key=lambda n: abs(n.center[1] - node.center[1])
   2878                     + abs(n.center[0] - node.center[0]) // 4,
   2879                     default=None,
   2880                 )
   2881                 near.append(f"{node.cls.rsplit('.', 1)[-1]}@{node.center}"
   2882                             f"~{label.label[:18] if label else '?'}")
   2883             c.note(f"{where}: {len(unnamed)} unnamed clickables: {near}")
   2884         else:
   2885             c.note(f"{where}: all clickable elements are named")
   2886         c.check()
   2887 
   2888     c.back_to_home()
   2889     audit("main")
   2890     c.app.open_settings()
   2891     audit("settings")
   2892     for label, where in ((r"(?i)^Payment services$", "exchange list"),
   2893                          (r"(?i)^Bank accounts$", "bank accounts")):
   2894         c.app.open_settings()
   2895         try:
   2896             c.app.scroll_to_text(label, max_scrolls=10)
   2897         except TimeoutError:
   2898             continue
   2899         if c.tap(label):
   2900             audit(where)
   2901     c.back_to_home()
   2902     for label, where in ((r"(?i)^Send$", "peer send"), (r"(?i)^Request$", "peer request"),
   2903                          (r"(?i)^Deposit$", "deposit"), (r"(?i)^Withdraw$", "withdraw")):
   2904         c.back_to_home()
   2905         if c.tap(label, timeout=15):
   2906             audit(where)
   2907     screen = open_transactions(c)
   2908     rows = transaction_rows(screen)
   2909     if rows:
   2910         c.dev.tap_node(rows[0], screen)
   2911         time.sleep(2)
   2912         audit("transaction detail")
   2913     c.note(f"summary: {visited}")
   2914     c.check()
   2915 
   2916 
   2917 @scenario("exchange_url_fuzz", setup="fresh",
   2918           about="hostile payment-service URLs in the add-exchange field")
   2919 def s_exchange_url_fuzz(c: Ctx) -> None:
   2920     urls = [
   2921         "",
   2922         "not a url",
   2923         "http://",
   2924         "http://localhost:9/",                  # nothing listening
   2925         "http://localhost:8082/",               # a bank, not an exchange
   2926         "https://localhost:8081/",              # right host, wrong scheme
   2927         "http://localhost:8081/../../etc/passwd",
   2928         "http://127.0.0.1:8081/",               # same exchange, other spelling
   2929         "http://localhost:8081/" + "a" * 500,
   2930         "http://日本語.example/",
   2931         "javascript:alert(1)",
   2932         "file:///etc/passwd",
   2933     ]
   2934     # The dialog closes back onto the exchange list, so the list is opened
   2935     # once and every address goes through from there.
   2936     open_exchange_list(c)
   2937     for url in urls:
   2938         if not c.tap(r"(?i)^Add payment service$", timeout=20):
   2939             c.note("no add-payment-service entry; "
   2940                    + str(c.dev.dump().texts()[:8]))
   2941             break
   2942         screen = c.see(r"(?i)Enter address of payment service|address", timeout=20)
   2943         fields = screen.editable() if screen else []
   2944         if not fields:
   2945             c.note("no URL field")
   2946             c.dev.back()
   2947             continue
   2948         c.dev.tap_node(fields[0], screen)
   2949         if url:
   2950             c.dev.type_text(url)
   2951         c.tap(r"(?i)^OK$|^Add$|^Continue$|^Next$", timeout=10)
   2952         time.sleep(2)
   2953         after = c.dev.dump()
   2954         c.note(f"{url[:46]!r} -> {after.texts()[:8]}")
   2955         c.check()
   2956         if after.find(r"(?i)Enter address of payment service") is not None:
   2957             # The dialog stayed open (it should, with an error); close it.
   2958             c.tap(r"(?i)^Cancel$", timeout=6)
   2959     c.ep.check_database()
   2960 
   2961 
   2962 @scenario("peer_expiry_custom", setup="funded",
   2963           about="the peer-send expiry picker, including a custom period")
   2964 def s_peer_expiry(c: Ctx) -> None:
   2965     c.back_to_home()
   2966     c.must_tap(r"(?i)^Send$", timeout=30)
   2967     c.require(r"(?i)Send money|Amount to send|Purpose", timeout=30)
   2968     c.set_amount("€5.00", "500")
   2969     for option in (r"(?i)^1 day$", r"(?i)^1 week$", r"(?i)^30 days$", r"(?i)^Custom$"):
   2970         if not c.tap(r"(?i)Expires in|^1 week$|^1 day$|^30 days$|^Custom$", timeout=8):
   2971             break
   2972         if c.tap(option, timeout=8):
   2973             c.note(f"picked {option}")
   2974             c.check()
   2975     # Custom opens day and hour fields.
   2976     screen = c.dev.dump()
   2977     if screen.find(r"(?i)^Days$|^Hours$"):
   2978         c.note("custom expiry fields: " + str(screen.texts()[:10]))
   2979         c.fill("3", 1)
   2980         c.check()
   2981     c.tap(r"(?i)^Send ", timeout=20)
   2982     time.sleep(4)
   2983     c.note("after send: " + str(c.dev.dump().texts()[:10]))
   2984     c.check()
   2985     c.ep.check_database()
   2986 
   2987 
   2988 @scenario("deposit_methods", setup="funded",
   2989           about="all three deposit account types and their validation")
   2990 def s_deposit_methods(c: Ctx) -> None:
   2991     c.app.open_settings()
   2992     c.app.scroll_to_text(r"(?i)^Bank accounts$")
   2993     c.must_tap(r"(?i)^Bank accounts$")
   2994     c.require(r"(?i)Known bank accounts|No bank accounts saved|Add account", timeout=25)
   2995     if not c.tap(r"(?i)^Add account$", timeout=20):
   2996         c.note("no add-account entry")
   2997         return
   2998     c.require(r"(?i)IBAN|x-taler-bank|Bitcoin|Account holder", timeout=25)
   2999     cases = [
   3000         (r"(?i)^IBAN$", [("Holder One", 0), ("DE89370400440532013000", 1)]),
   3001         (r"(?i)^x-taler-bank$", [("Holder Two", 0), ("http://localhost:8082/wallet1", 1)]),
   3002         # The Bitcoin tab has no holder field: its first field is the address
   3003         # and the second is the note.  Filling them the other way round sent
   3004         # `payto://bitcoin/Holder%20Three` and read as a wallet defect.
   3005         (r"(?i)^Bitcoin$", [("bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh", 0),
   3006                             ("Holder Three", 1)]),
   3007     ]
   3008     for tab, fields in cases:
   3009         # A successful submit closes the form and goes back to the account
   3010         # list, so every case has to open it again -- without this the first
   3011         # case to succeed left the later tabs with no form to tap, and the
   3012         # Bitcoin one was never tried ("no Bitcoin tab").
   3013         if c.dev.dump().find(r"(?i)^Note$") is None:
   3014             if not c.tap_button(r"(?i)^Add account$", timeout=15):
   3015                 c.note("could not reopen the add-account form")
   3016                 break
   3017             # "IBAN" is also the wire method printed on an account *row*, so
   3018             # requiring it matches the list we just came from; the note field
   3019             # exists only on the form.
   3020             if c.see(r"(?i)^Note$", timeout=20) is None:
   3021                 c.note("the add-account form did not reopen: "
   3022                        + str(c.dev.dump().texts()[:10]))
   3023                 break
   3024         if not c.tap(tab, timeout=10):
   3025             c.note(f"no {tab} tab: " + str(c.dev.dump().texts()[:10]))
   3026             continue
   3027         c.check()
   3028         for value, index in fields:
   3029             c.fill(value, index, clear=True)
   3030         # Every type needs the unmarked "Note" field, or the submit button
   3031         # stays disabled and the account is never added -- which is how this
   3032         # scenario reported "ok" while adding nothing.
   3033         name = re.sub(r"[^A-Za-z-]", "", tab.replace("(?i)", ""))
   3034         fill_account_note(c, f"Simulator {name}")
   3035         time.sleep(1)
   3036         screen = c.dev.dump()
   3037         complaints = [t for t in screen.texts()
   3038                       if "invalid" in t.lower() or "error" in t.lower()]
   3039         c.note(f"{tab}: complaints={complaints[:2]} labels={screen.texts()[:8]}")
   3040         c.tap_button(r"(?i)^Add account$|^Save$|^OK$", timeout=8)
   3041         time.sleep(3)
   3042         c.note(f"{tab} after submitting: {c.dev.dump().texts()[:10]}")
   3043         c.check()
   3044     c.ep.check_database()
   3045 
   3046 
   3047 @scenario("deposit_bad_payto", setup="funded",
   3048           about="deposit to an account the exchange will reject, then read the "
   3049                 "failed transaction")
   3050 def s_deposit_bad_payto(c: Ctx) -> None:
   3051     # A syntactically fine IBAN that belongs to nobody: the deposit should be
   3052     # accepted by the wallet and then fail, which is the only cheap way to
   3053     # reach the failed-transaction screens.
   3054     bad = "payto://iban/SANDBOXX/DE02100100109307118603?receiver-name=Nobody"
   3055     c.app.handle_uri(bad)
   3056     time.sleep(3)
   3057     screen = c.dev.dump()
   3058     c.note("payto prompt: " + str(screen.texts()[:12]))
   3059     c.check()
   3060     if screen.editable():
   3061         # Amount fields take digits from the right: "100" is 1.00, and "1"
   3062         # made a one-cent deposit.  No clear=True: on this field the 80
   3063         # KEYCODE_DELs leave it at 0.00 and the typed digits do not land, so
   3064         # the submit button stays disabled.
   3065         c.fill("100")
   3066     # The button on this screen is "Send", not "Deposit": tapping for the
   3067     # latter did nothing at all, and the scenario then read the funding
   3068     # withdrawal's detail and called it a failed deposit.
   3069     tap_if_any(c, (r"(?i)^Check fees$",))
   3070     if not c.tap_button(r"(?i)^Send$|^Make deposit$|^Deposit$", timeout=20):
   3071         c.note("nothing to submit the deposit with: "
   3072                + str(c.dev.dump().texts()[:12]))
   3073     time.sleep(8)
   3074     c.note("after depositing: " + str(c.dev.dump().texts()[:12]))
   3075     c.check()
   3076     # Whatever state it reached, look at the transaction and its actions.
   3077     screen = open_transactions(c)
   3078     rows = transaction_rows(screen)
   3079     if rows:
   3080         c.dev.tap_node(rows[0], screen)
   3081         time.sleep(2)
   3082         detail = c.dev.dump()
   3083         c.note("deposit detail: " + str(detail.texts()[:12]))
   3084         # A transaction that carries an error shows an "Error" button in
   3085         # developer mode, and it is the only way into
   3086         # ErrorTransactionComposable's dialog -- the error object as JSON, with
   3087         # a copy button.
   3088         if c.tap(r"(?i)^Error$", timeout=10):
   3089             dialog = c.dev.dump()
   3090             c.note("the error dialog: " + str(dialog.texts()[:10]))
   3091             c.check()
   3092             c.tap(r"(?i)^OK$|^Close$|^Cancel$|^Copy$", timeout=8)
   3093             time.sleep(1.5)
   3094         else:
   3095             c.note("no Error button on the failed deposit: "
   3096                    + str([n.label for n in detail.tappable() if n.label][:10]))
   3097         for action in (r"(?i)^Retry$", r"(?i)^Abandon$", r"(?i)^Abort$"):
   3098             if c.tap(action, timeout=8):
   3099                 c.tap(r"(?i)^Abandon$|^Abort$|^OK$|^Yes$", timeout=6)
   3100                 time.sleep(2)
   3101                 c.check()
   3102                 break
   3103     c.check()
   3104     c.ep.check_database()
   3105 
   3106 
   3107 @scenario("withdraw_to_dead_exchange", setup="fresh",
   3108           about="withdraw from an exchange that is not listening",
   3109           expects=("background-error", "stuck-operation", "error-screen"))
   3110 def s_withdraw_dead_exchange(c: Ctx) -> None:
   3111     c.app.handle_uri("taler+http://withdraw-exchange/localhost:9/")
   3112     time.sleep(5)
   3113     screen = c.dev.dump()
   3114     c.note("dead exchange: " + str(screen.texts()[:12]))
   3115     c.check()
   3116     c.tap(r"(?i)^Retry$", timeout=10)
   3117     time.sleep(4)
   3118     c.check()
   3119     c.back_to_home()
   3120     rows = transaction_rows(open_transactions(c))
   3121     c.note(f"{len(rows)} transactions after the failed attempt")
   3122     if rows:
   3123         screen = open_transactions(c)
   3124         c.dev.tap_node(transaction_rows(screen)[0], screen)
   3125         time.sleep(2)
   3126         c.note("failed withdrawal detail: " + str(c.dev.dump().texts()[:12]))
   3127         c.check()
   3128     c.ep.check_database()
   3129 
   3130 
   3131 @scenario("withdraw_account_details", setup="funded",
   3132           about="the manual withdrawal's account picker and wire details")
   3133 def s_withdraw_account_details(c: Ctx) -> None:
   3134     c.back_to_home()
   3135     c.must_tap(r"(?i)^Withdraw$", timeout=30)
   3136     c.require(r"(?i)Amount to withdraw|Select target bank account|Payment service",
   3137               timeout=30)
   3138     c.set_amount("€5.00", "500")
   3139     c.check()
   3140     # Tapping the age row opens the picker, which covers the confirm button, so
   3141     # an age has to be chosen before confirming; the age path itself is
   3142     # withdraw_age_restricted's job.
   3143     if c.tap(r"(?i)Restrict usage to age|Unrestricted", timeout=6):
   3144         if not c.tap(r"(?i)^Unrestricted$|^18$", timeout=8):
   3145             c.dev.back()
   3146         time.sleep(1)
   3147     c.accept_tos()
   3148     c.must_tap(r"(?i)Confirm withdrawal|^Withdraw$", timeout=25)
   3149     # A manual withdrawal waits for a wire transfer, and its detail screen
   3150     # links to the instructions.
   3151     screen = c.require(r"(?i)Wire transfer instructions|transaction is pending",
   3152                        timeout=45)
   3153     c.note("pending withdrawal: " + str(screen.texts()[:12]))
   3154     c.check()
   3155     c.must_tap(r"(?i)Wire transfer instructions", timeout=25)
   3156     screen = c.require(r"(?i)Subject|Recipient|IBAN|Account", timeout=30)
   3157     c.note("transfer instructions: " + str(screen.texts()[:16]))
   3158     c.check()
   3159     # Copy buttons, the QR variants and the hand-off to a banking app.
   3160     copies = [n for n in screen.tappable() if n.label.strip().lower() == "copy"]
   3161     c.note(f"{len(copies)} copy buttons")
   3162     if copies:
   3163         c.dev.tap_node(copies[0], screen)
   3164         time.sleep(1)
   3165         c.check()
   3166     for label in (r"(?i)Wire transfer QR codes", r"(?i)EPC QR", r"(?i)Swiss QR bill",
   3167                   r"(?i)Unknown payment QR", r"(?i)Open in banking app",
   3168                   r"(?i)^Share$"):
   3169         try:
   3170             c.app.scroll_to_text(label, max_scrolls=4)
   3171         except TimeoutError:
   3172             continue
   3173         c.note(f"saw {label}")
   3174         if "Share" not in label and "banking app" not in label:
   3175             c.tap(label, timeout=6)
   3176             c.check()
   3177     c.ep.check_database()
   3178 
   3179 
   3180 @scenario("withdraw_account_tabs", setup="funded",
   3181           about="every wire account the exchange offers for a manual withdrawal")
   3182 def s_withdraw_account_tabs(c: Ctx) -> None:
   3183     """One transfer screen per wire method.
   3184 
   3185     `TransferAccountChooser` only appears once the exchange advertises more
   3186     than one account, and the IBAN and Bitcoin transfer screens are only
   3187     reachable through it.
   3188     """
   3189     c.back_to_home()
   3190     c.must_tap(r"(?i)^Withdraw$", timeout=30)
   3191     c.require(r"(?i)Amount to withdraw|Select target bank account|Payment service",
   3192               timeout=30)
   3193     c.set_amount("€5.00", "500")
   3194     # Deliberately leave the age chooser alone: tapping it opens the age picker
   3195     # and hides the confirm button, and the age path has its own scenario.
   3196     c.accept_tos()
   3197     c.must_tap(r"(?i)Confirm withdrawal|^Withdraw$", timeout=25)
   3198     screen = c.require(r"(?i)Wire transfer instructions|transaction is pending",
   3199                        timeout=45)
   3200     c.note("pending withdrawal screen: " + str(screen.texts()))
   3201     tabs = [t for t in screen.texts() if re.match(r"(?i)^Account #\d", t.strip())]
   3202     c.note(f"account tabs: {tabs}")
   3203     if not tabs:
   3204         c.note("the exchange advertises a single wire account; nothing to choose")
   3205     for tab in tabs or [None]:
   3206         if tab is not None:
   3207             # Tap the tab by its node: the label carries parentheses and the
   3208             # account index, which is awkward to match as a pattern.
   3209             screen = c.dev.dump()
   3210             node = next((n for n in screen.labelled()
   3211                          if n.label.strip() == tab.strip()), None)
   3212             if node is None:
   3213                 c.note(f"could not find the tab {tab!r} again")
   3214                 continue
   3215             # Tap the tab's own centre: the neighbour search in tap_target
   3216             # would reach the app bar's back arrow, which is within its reach.
   3217             c.dev.tap(*node.center)
   3218             time.sleep(2)
   3219         c.check()
   3220         try:
   3221             c.app.scroll_to_text(r"(?i)Wire transfer instructions", max_scrolls=4)
   3222         except TimeoutError:
   3223             c.note(f"{tab}: no instructions link; screen "
   3224                    + str(c.dev.dump().texts()))
   3225             continue
   3226         if not c.tap(r"(?i)Wire transfer instructions", timeout=20):
   3227             c.note(f"{tab}: the instructions link would not tap")
   3228             continue
   3229         # Each method has its own labels: a subject and a recipient for
   3230         # x-taler-bank, an IBAN block for IBAN, and a split transaction with
   3231         # segwit outputs for Bitcoin.
   3232         screen = c.require(r"(?i)Subject|Recipient|IBAN|Account|Address|"
   3233                            r"split transaction|BTC", timeout=30)
   3234         c.note(f"{tab} instructions: {screen.texts()[:14]}")
   3235         if screen.find(r"(?i)BTC") is not None:
   3236             amounts = [t for t in screen.texts() if "BTC" in t]
   3237             c.note(f"{tab}: amounts labelled BTC: {amounts[:4]}")
   3238         c.check()
   3239         # Each method renders its own transfer screen; the QR variants hang off
   3240         # it and differ per method (EPC for IBAN, none for Bitcoin).
   3241         for label in (r"(?i)Wire transfer QR codes", r"(?i)EPC QR",
   3242                       r"(?i)Swiss QR bill", r"(?i)Unknown payment QR"):
   3243             try:
   3244                 c.app.scroll_to_text(label, max_scrolls=3)
   3245             except TimeoutError:
   3246                 continue
   3247             c.note(f"{tab}: saw {label}")
   3248             c.tap(label, timeout=6)
   3249             c.check()
   3250         c.dev.back()
   3251         c.require(r"(?i)Wire transfer instructions|transaction is pending", timeout=25)
   3252     c.ep.check_database()
   3253 
   3254 
   3255 def second_exchange_or_skip(c: Ctx) -> Optional[str]:
   3256     """The second exchange's URL, or None with a note saying why not.
   3257 
   3258     exchange2.sh runs it beside the stack; it is not part of the stack itself,
   3259     so a scenario that needs two payment services has to cope without one.
   3260     """
   3261     url = getattr(c.env, "exchange2", None) or SECOND_EXCHANGE
   3262     try:
   3263         import urllib.request
   3264         with urllib.request.urlopen(url + "config", timeout=5) as r:
   3265             if r.status != 200:
   3266                 raise RuntimeError(f"HTTP {r.status}")
   3267     except Exception as e:  # noqa: BLE001 - absence is a skip, not a failure
   3268         c.note(f"no second exchange at {url} ({str(e)[:60]}); nothing to choose")
   3269         return None
   3270     # Reachable from here is not reachable from the emulator: without the
   3271     # reverse mapping the wallet adds nothing and says nothing about it, which
   3272     # looks exactly like a scenario that worked.
   3273     port = url.rstrip("/").rsplit(":", 1)[-1]
   3274     if f"tcp:{port}" not in c.dev.adb("reverse", "--list", check=False):
   3275         c.note(f"port {port} is not mapped into {c.dev.serial}; "
   3276                f"the wallet cannot reach the second exchange")
   3277         return None
   3278     return url
   3279 
   3280 
   3281 def service_or_skip(c: Ctx, url: str, what: str) -> Optional[str]:
   3282     """A service beside the stack, if it is up and the emulator can reach it."""
   3283     try:
   3284         import urllib.request
   3285         with urllib.request.urlopen(url + "config", timeout=5) as r:
   3286             if r.status != 200:
   3287                 raise RuntimeError(f"HTTP {r.status}")
   3288     except Exception as e:  # noqa: BLE001 - absence is a skip, not a failure
   3289         c.note(f"no {what} at {url} ({str(e)[:60]})")
   3290         return None
   3291     port = url.rstrip("/").rsplit(":", 1)[-1]
   3292     if f"tcp:{port}" not in c.dev.adb("reverse", "--list", check=False):
   3293         c.note(f"port {port} is not mapped into {c.dev.serial}; "
   3294                f"the wallet cannot reach the {what}")
   3295         return None
   3296     return url
   3297 
   3298 
   3299 def add_exchange_by_url(c: Ctx, url: str) -> None:
   3300     """Settings -> Payment services -> Add, typing a URL."""
   3301     open_exchange_list(c)
   3302     c.must_tap(r"(?i)^Add payment service$")
   3303     screen = c.require(r"(?i)Enter address of payment service|address", timeout=30)
   3304     fields = screen.editable()
   3305     if not fields:
   3306         raise RuntimeError(f"no URL field on the add screen: {screen.texts()}")
   3307     c.dev.tap_node(fields[0], screen)
   3308     c.dev.type_text(url)
   3309     c.tap(r"(?i)^Add$|^OK$|^Continue$|^Next$")
   3310     time.sleep(4)
   3311     # Adding one may ask for its terms of service.
   3312     c.tap(r"(?i)^Accept Terms of Service$|^Accept$|I accept", timeout=8)
   3313     time.sleep(2)
   3314     c.check()
   3315 
   3316 
   3317 @scenario("exchange_two_services", setup="fresh",
   3318           about="two payment services in the same currency, side by side")
   3319 def s_exchange_two_services(c: Ctx) -> None:
   3320     second = second_exchange_or_skip(c)
   3321     if second is None:
   3322         return
   3323     add_exchange_by_url(c, LOCAL_EXCHANGE)
   3324     add_exchange_by_url(c, second)
   3325     open_exchange_list(c)
   3326     screen = c.require(r"(?i)Currency:|localhost", timeout=25)
   3327     listed = [t for t in screen.texts() if "localhost" in t]
   3328     c.note(f"payment services listed: {listed}")
   3329     if len(listed) < 2:
   3330         c.note("WARNING: the second payment service is not listed")
   3331     c.check()
   3332     # The per-exchange menu, which is how the app exposes anything about one:
   3333     # tapping the URL itself does not navigate.
   3334     for which in ("8081", "8091"):
   3335         open_exchange_list(c)
   3336         if not exchange_menu(c, f"localhost:{which}"):
   3337             c.note(f"no menu for localhost:{which}")
   3338             continue
   3339         time.sleep(1.5)
   3340         c.note(f"{which} menu: {c.dev.dump().texts()[:14]}")
   3341         c.check()
   3342         c.dev.back()
   3343     c.ep.check_database()
   3344 
   3345 
   3346 @scenario("withdraw_pick_exchange", setup="funded",
   3347           about="the manual withdrawal's payment-service dropdown")
   3348 def s_withdraw_pick_exchange(c: Ctx) -> None:
   3349     """Choosing which payment service to withdraw from.
   3350 
   3351     This was written for `SelectExchangeDialogFragment`, on the assumption that
   3352     a withdrawal with two candidates would raise it.  It does not:
   3353     **that fragment has no caller anywhere in the app** (the last
   3354     DialogFragment left, and dead), and the bank-integrated prompt has no
   3355     service row at all -- its exchange is fixed, and the prompt shows only the
   3356     amount, the age restriction and "Confirm withdrawal".
   3357 
   3358     The real control is on the *manual* withdraw screen: an
   3359     `AmountScopeField` whose "via <service>" row is an exposed dropdown over
   3360     the known scopes.  It is `clickable` but **disabled** until the service's
   3361     terms are accepted, which is what made every earlier attempt tap a
   3362     neighbour and leave the screen.
   3363     """
   3364     second = second_exchange_or_skip(c)
   3365     if second is None:
   3366         return
   3367     add_exchange_by_url(c, second)
   3368     c.back_to_home()
   3369     c.must_tap(r"(?i)^Withdraw$", timeout=30)
   3370     screen = c.require(r"(?i)Amount to withdraw|Select target|Payment service|via",
   3371                        timeout=30)
   3372     c.note("the manual withdraw screen: " + str(screen.texts()[:18]))
   3373     c.check()
   3374     # Terms first: the dropdown is disabled until they are accepted.
   3375     c.accept_tos()
   3376     row = next((n for n in c.dev.dump().labelled()
   3377                 if re.match(r"(?i)^https?://", n.label.strip())), None)
   3378     if row is None:
   3379         c.note("no payment-service row on the withdraw screen")
   3380         return
   3381     target = c.dev.dump().tap_target(row)
   3382     c.note(f"the service row {row.label!r}: clickable={target.clickable} "
   3383            f"enabled={target.enabled}")
   3384     if not target.enabled:
   3385         c.note("the service row is still disabled after accepting the terms")
   3386         c.check()
   3387         return
   3388     c.dev.tap_node(target)
   3389     time.sleep(2)
   3390     opened = c.dev.dump()
   3391     c.note("after opening the dropdown: " + str(opened.texts()[:18]))
   3392     c.check()
   3393     # The menu lists one entry per known scope.
   3394     if c.tap(r"(?i)localhost:8091|8091", timeout=10):
   3395         time.sleep(2)
   3396         c.note("picked the second service: " + str(c.dev.dump().texts()[:14]))
   3397     else:
   3398         c.note("the second service is not among the scopes offered")
   3399     c.check()
   3400     c.set_amount("€5.00", "500")
   3401     c.accept_tos()
   3402     c.tap_button(r"(?i)Confirm withdrawal|^Withdraw", timeout=25)
   3403     time.sleep(5)
   3404     c.note("after confirming: " + str(c.dev.dump().texts()[:16]))
   3405     c.check()
   3406     c.ep.check_database()
   3407 
   3408 
   3409 @scenario("balances_two_exchanges", setup="fresh",
   3410           about="coins from two payment services in one currency")
   3411 def s_balances_two_exchanges(c: Ctx) -> None:
   3412     """Two services in one currency is what creates a second balance scope,
   3413     and what "treat as global" is for."""
   3414     second = second_exchange_or_skip(c)
   3415     if second is None:
   3416         return
   3417     # Coins from the stack's exchange, through the bank as usual.
   3418     flows.withdraw(c.app, c.bank, "EUR:10")
   3419     c.app.home()
   3420     add_exchange_by_url(c, second)
   3421     c.back_to_home()
   3422     screen = c.dev.dump()
   3423     c.note("home with two services: " + str(screen.texts()[:18]))
   3424     c.check()
   3425     # The balance detail and its transaction list, per scope.
   3426     if c.tap(r"(?i)^€|EUR", timeout=10):
   3427         time.sleep(2)
   3428         c.note("balance detail: " + str(c.dev.dump().texts()[:16]))
   3429         c.check()
   3430     c.back_to_home()
   3431     # "Treat as global" lives in the per-exchange menu and is where a null
   3432     # master key used to come from.
   3433     open_exchange_list(c)
   3434     # Contact each service before treating it as global: "treat as global"
   3435     # sends the master public key, which is null until the exchange's /keys
   3436     # has been fetched, and a null one is dropped from the request --
   3437     # findings/addglobalcurrencyexchange-null-masterpub.md.  The second
   3438     # service is the one that arrives un-contacted, with its terms
   3439     # unaccepted.
   3440     for which in ("8081", "8091"):
   3441         if not exchange_menu(c, f"localhost:{which}"):
   3442             continue
   3443         time.sleep(1)
   3444         if c.tap(r"(?i)^Accept Terms of Service$", timeout=6):
   3445             time.sleep(2)
   3446             c.accept_tos()
   3447             open_exchange_list(c)
   3448             exchange_menu(c, f"localhost:{which}")
   3449             time.sleep(1)
   3450         if c.tap(r"(?i)^Reload information$", timeout=8):
   3451             time.sleep(4)
   3452             c.note(f"{which}: reloaded")
   3453         open_exchange_list(c)
   3454     for which in ("8081", "8091"):
   3455         if not exchange_menu(c, f"localhost:{which}"):
   3456             c.note(f"no menu for localhost:{which}")
   3457             continue
   3458         time.sleep(1)
   3459         c.note(f"{which} menu: {c.dev.dump().texts()[:12]}")
   3460         if c.tap(r"(?i)Treat as global|global currency", timeout=8):
   3461             time.sleep(3)
   3462             c.note(f"{which} after treat-as-global: {c.dev.dump().texts()[:12]}")
   3463         c.check()
   3464         open_exchange_list(c)
   3465 
   3466     # With both services global, the currency scope carries both their shopping
   3467     # URLs, and the card goes to ExchangeShoppingScreen rather than straight
   3468     # out to a browser -- MainScreen.kt:188 opens the browser when there is
   3469     # exactly one URL, so one service can never reach that screen.
   3470     c.back_to_home()
   3471     try:
   3472         c.app.scroll_to_text(r"(?i)^Where to pay with ", max_scrolls=6)
   3473     except TimeoutError:
   3474         c.note("no shopping card on the main screen: "
   3475                + str(c.dev.dump().texts()[:16]))
   3476         c.check()
   3477         c.ep.check_database()
   3478         return
   3479     if not c.tap(r"(?i)^Where to pay with ", timeout=10):
   3480         c.note("the shopping card would not tap")
   3481     else:
   3482         time.sleep(3)
   3483         screen = c.dev.dump()
   3484         # Recognised by the screen's own message rather than its title: the
   3485         # title reads "Where to pay with EUR", which is also what the card on
   3486         # the main screen says, so matching the title cannot tell the two
   3487         # apart.
   3488         if screen.find(r"(?i)offers the following website") is not None:
   3489             c.note("the shopping screen: " + str(screen.texts()[:12]))
   3490             # Each row is one exchange's shopping URL; opening one leaves the
   3491             # app, so the list itself is what is checked here.
   3492             rows = [n for n in screen.labelled() if "http" in n.label.lower()]
   3493             c.note(f"{len(rows)} shopping URLs listed: "
   3494                    + str([n.label[:40] for n in rows]))
   3495         else:
   3496             # MainScreen.kt:188 only navigates when the scope carries more than
   3497             # one shopping URL; with one it opens the URL instead, which is
   3498             # what this means.
   3499             c.note("the card did not open the shopping screen, so the scope "
   3500                    "still carries one shopping URL: "
   3501                    + str(screen.texts()[:12]))
   3502     c.check()
   3503     c.ep.check_database()
   3504 
   3505 
   3506 @scenario("revoke_denomination", setup="funded",
   3507           about="revoke a denomination the wallet holds and watch the recoup",
   3508           # Revocation is supposed to make the wallet give the coins back to
   3509           # the exchange and get new ones; errors along the way are the point.
   3510           expects=("background-error", "stuck-operation", "internal-error-code",
   3511                    "error-screen", "core-internal"))
   3512 def s_revoke_denomination(c: Ctx) -> None:
   3513     """What happens when the exchange withdraws a denomination under the wallet.
   3514 
   3515     Destructive and stack-wide -- the denomination stays revoked until the
   3516     stack is started again -- so this only runs when a phase says so with
   3517     SIM_DESTRUCTIVE=1.
   3518     """
   3519     if os.environ.get("SIM_DESTRUCTIVE") != "1":
   3520         c.note("destructive scenarios are off; set SIM_DESTRUCTIVE=1 in a phase")
   3521         return
   3522     import dbprobe
   3523     c.back_to_home()
   3524     before = c.dev.dump()
   3525     c.note("balance before: " + str(before.texts()[:8]))
   3526 
   3527     db = dbprobe.pull(c.dev)
   3528     held = dbprobe.rows(db, "select denom_pub_hash, count(*) c from coins "
   3529                             "where status = 'fresh' group by denom_pub_hash "
   3530                             "order by c asc", limit=10)
   3531     if not held:
   3532         c.note("the wallet holds no fresh coins; nothing to revoke")
   3533         return
   3534     c.note(f"the wallet holds {len(held)} denominations: "
   3535            + str([r["c"] for r in held]))
   3536     # The one it holds fewest of: enough to force a recoup without taking the
   3537     # whole balance away.
   3538     target = held[0]["denom_pub_hash"]
   3539     try:
   3540         crock = stack_mod.revoke_denomination(target)
   3541     except Exception as e:  # noqa: BLE001 - reported as a note, not a crash
   3542         c.note(f"could not revoke: {str(e)[:200]}")
   3543         return
   3544     c.note(f"revoked {crock} ({held[0]['c']} coin(s) held)")
   3545 
   3546     # The wallet learns about it from /keys, which it re-reads on its own
   3547     # schedule.  Opening the exchange list is not enough; the menu has a
   3548     # "Reload information" entry, which is the user's way of asking.
   3549     open_exchange_list(c)
   3550     if exchange_menu(c):
   3551         time.sleep(1)
   3552         if c.tap(r"(?i)^Reload information$", timeout=10):
   3553             c.note("asked the wallet to reload the exchange")
   3554             time.sleep(8)
   3555     c.back_to_home()
   3556     for _ in range(20):
   3557         time.sleep(6)
   3558         screen = c.dev.dump()
   3559         if screen.find(r"(?i)recoup|loss of funds") is not None:
   3560             c.note("something about a recoup or a loss appeared")
   3561             break
   3562     c.note("home after revocation: " + str(c.dev.dump().texts()[:12]))
   3563     c.check()
   3564     open_transactions(c)
   3565     c.note("transactions after revocation: "
   3566            + str(c.dev.dump().texts()[:16]))
   3567     c.check()
   3568     # The database knows about losses and recoups even when the screens say
   3569     # nothing.  A revocation the wallet has seen leaves a trace in one of
   3570     # these; nothing in any of them means it never noticed.
   3571     db = dbprobe.pull(c.dev)
   3572     for table in ("denom_loss_events", "recoup_groups", "coins"):
   3573         try:
   3574             rows = dbprobe.rows(db, f"select * from {table}", limit=3)
   3575             c.note(f"{table}: {len(rows)} rows")
   3576         except Exception as e:  # noqa: BLE001
   3577             c.note(f"{table}: {str(e)[:80]}")
   3578     try:
   3579         rows = dbprobe.rows(db, "select status, count(*) c from coins "
   3580                                 "group by status", limit=8)
   3581         c.note("coins by status: " + str([dict(r) for r in rows]))
   3582     except Exception as e:  # noqa: BLE001
   3583         c.note(f"coin status: {str(e)[:80]}")
   3584     log = c.dev.logcat(lines=600)
   3585     hits = [l for l in log.splitlines()
   3586             if "recoup" in l.lower() or "revok" in l.lower()][:3]
   3587     c.note("the log on recoup/revocation: " + (" / ".join(hits)[:300] or "nothing"))
   3588 
   3589     # Recoup is how the money comes back, and it is a background task: the
   3590     # first measurement above catches the coin marked `denom-loss` and the
   3591     # balance down by its value, which is the *start* of the story.  Whether
   3592     # the wallet ends up whole is the question worth answering, so wait for
   3593     # the recoup group to finish and say what the balance did.
   3594     def shown_balance() -> str:
   3595         """The first euro amount on the main screen, as text."""
   3596         c.back_to_home()
   3597         for t in c.dev.dump().texts():
   3598             m = re.search(r"€\s*([0-9]+[.,][0-9]{2})", t)
   3599             if m:
   3600                 return m.group(1)
   3601         return "?"
   3602 
   3603     before = shown_balance()
   3604     settled = False
   3605     for _ in range(20):
   3606         time.sleep(15)
   3607         db = dbprobe.pull(c.dev)
   3608         try:
   3609             pending = dbprobe.rows(
   3610                 db, "select recoup_group_id, operation_status, timestamp_finished "
   3611                     "from recoup_groups where timestamp_finished is null", limit=5)
   3612         except Exception as e:  # noqa: BLE001
   3613             c.note(f"recoup_groups: {str(e)[:80]}")
   3614             break
   3615         if not pending:
   3616             settled = True
   3617             break
   3618     c.note(f"the recoup group finished within five minutes: {settled}")
   3619     after = shown_balance()
   3620     c.note(f"balance before the wait: {before}, after: {after}")
   3621     db = dbprobe.pull(c.dev)
   3622     try:
   3623         rows = dbprobe.rows(db, "select status, count(*) c from coins "
   3624                                 "group by status", limit=8)
   3625         c.note("coins by status once settled: " + str([dict(r) for r in rows]))
   3626     except Exception as e:  # noqa: BLE001
   3627         c.note(f"coin status: {str(e)[:80]}")
   3628     screen = open_transactions(c)
   3629     c.note("history once settled: " + str(screen.texts()[:16]))
   3630     c.check()
   3631 
   3632     # A revocation is the one thing in this stack that makes a *EUR* loss
   3633     # event, and therefore the only way to the loss transaction and its detail
   3634     # screen: the dev experiment's injected loss is hard-coded to TESTKUDOS
   3635     # (dev-experiments.ts:243), which a euro wallet has no scope to show it
   3636     # under.  `TransactionDenomLoss` and `TransitionLossComposable` have never
   3637     # rendered for that reason.
   3638     row = screen.find(r"(?i)^Loss of funds$")
   3639     if row is None:
   3640         try:
   3641             screen = c.app.scroll_to_text(r"(?i)^Loss of funds$", max_scrolls=6)
   3642             row = screen.find(r"(?i)^Loss of funds$")
   3643         except TimeoutError:
   3644             row = None
   3645     if row is None:
   3646         c.note("no loss transaction in the history, though the database has "
   3647                "a loss event: " + str(screen.texts()[:16]))
   3648         c.check()
   3649         c.ep.check_database()
   3650         return
   3651     c.dev.tap_node(row, screen)
   3652     time.sleep(2.5)
   3653     detail = c.dev.dump()
   3654     c.note("the loss detail screen: " + str(detail.texts()[:16]))
   3655     # Its own labels: the reason, and one of the three explanations.
   3656     if detail.find(r"(?i)^Reason$") is None:
   3657         c.note("WARNING: the loss detail shows no reason")
   3658     reason = detail.find(r"(?i)not renewed|stopped offering|lost the record")
   3659     c.note(f"the loss reason is spelled out: {reason is not None}")
   3660     c.check()
   3661     c.ep.check_database()
   3662 
   3663 
   3664 @scenario("wallet_lock_without_credential", setup="funded",
   3665           about="turn the wallet lock on, then take the device credential away",
   3666           expects=("error-screen",))
   3667 def s_wallet_lock(c: Ctx) -> None:
   3668     """What happens to a locked wallet when the screen lock goes away.
   3669 
   3670     "Protect access to wallet" can only be switched on while the device can
   3671     authenticate (`enableBiometrics` checks `canAuthenticate`), but nothing
   3672     re-checks afterwards, and `BiometricOverlay` covers the whole app with a
   3673     single "Tap to unlock" button.  Removing the credential afterwards is an
   3674     ordinary thing to do.
   3675 
   3676     Touches the device's lock settings, so it only runs under
   3677     SIM_DESTRUCTIVE=1, and it clears the credential again whatever happens.
   3678     """
   3679     if os.environ.get("SIM_DESTRUCTIVE") != "1":
   3680         c.note("destructive scenarios are off; set SIM_DESTRUCTIVE=1 in a phase")
   3681         return
   3682     try:
   3683         out = c.dev.shell("locksettings set-pin 1234", check=False)
   3684         c.note(f"set a device PIN: {out.strip()[:80]}")
   3685         if "set" not in out.lower():
   3686             c.note("could not set a device credential; nothing to test")
   3687             return
   3688         c.app.open_settings()
   3689         c.app.scroll_to_text(r"(?i)^Protect access to wallet$")
   3690         c.must_tap(r"(?i)^Protect access to wallet$", timeout=20)
   3691         time.sleep(3)
   3692         c.note("after switching the lock on: " + str(c.dev.dump().texts()[:10]))
   3693         c.check()
   3694         # Locked now: a restart has to ask before showing anything.
   3695         c.dev.stop()
   3696         time.sleep(2)
   3697         c.dev.launch()
   3698         time.sleep(6)
   3699         locked = c.dev.dump()
   3700         # The overlay covers the app, but uiautomator still reports the nodes
   3701         # underneath it, so presence has to be asked about rather than read off
   3702         # the first few labels.
   3703         c.note(f"after a restart with a credential: locked="
   3704                f"{locked.find(r'(?i)Tap to unlock') is not None}; "
   3705                + str(locked.texts()[:8]))
   3706         if locked.find(r"(?i)Tap to unlock") is None:
   3707             c.note("the wallet is not locked; the switch did not take")
   3708             return
   3709         c.check()
   3710         # Now the credential goes away, as it does when a user turns their
   3711         # screen lock off.
   3712         out = c.dev.shell("locksettings clear --old 1234", check=False)
   3713         c.note(f"cleared the device credential: {out.strip()[:80]}")
   3714         c.dev.stop()
   3715         time.sleep(2)
   3716         c.dev.launch()
   3717         time.sleep(6)
   3718         screen = c.dev.dump()
   3719         c.note(f"after a restart with no credential: locked="
   3720                f"{screen.find(r'(?i)Tap to unlock') is not None}; "
   3721                + str(screen.texts()[:8]))
   3722         c.check()
   3723         if screen.find(r"(?i)Tap to unlock") is not None:
   3724             c.dev.logcat(clear=True)
   3725             c.must_tap(r"(?i)Tap to unlock", timeout=20)
   3726             time.sleep(5)
   3727             after = c.dev.dump()
   3728             still = after.find(r"(?i)Tap to unlock") is not None
   3729             c.note(f"after tapping unlock: still locked={still}; "
   3730                    + str(after.texts()[:8]))
   3731             # The prompt reports its refusal through a toast, which is not in
   3732             # the hierarchy; the log has it.
   3733             log = c.dev.logcat(lines=400)
   3734             lines = [l for l in log.splitlines()
   3735                      if "iometric" in l or "uthenticat" in l]
   3736             c.note("authentication log: " + " / ".join(lines[-3:])[:300])
   3737             c.check()
   3738             if still:
   3739                 c.note("WARNING: the wallet cannot be unlocked at all; the only "
   3740                        "way back in is clearing the app's data, which destroys "
   3741                        "the coins")
   3742     finally:
   3743         c.dev.shell("locksettings clear --old 1234", check=False)
   3744         c.dev.shell("locksettings set-disabled true", check=False)
   3745 
   3746 
   3747 # wallet-core can be told to fail a named operation from the outside, which is
   3748 # the only way to see what each screen does with an error it cannot otherwise
   3749 # be made to produce.  The detail is base64url JSON with a numeric code.
   3750 def api_error_uri(operation: str, code: int = 7001,
   3751                   hint: str = "injected by the simulator",
   3752                   count: int = 4) -> str:
   3753     import base64
   3754     detail_obj: dict = {"code": code}
   3755     if hint:
   3756         detail_obj["hint"] = hint
   3757     detail = base64.urlsafe_b64encode(
   3758         json.dumps(detail_obj).encode()).decode().rstrip("=")
   3759     return (f"taler+http://dev-experiment/api-error?operation={operation}"
   3760             f"&detail={detail}&count={count}")
   3761 
   3762 
   3763 @scenario("api_error_sweep", setup="funded",
   3764           about="make each screen's wallet-core call fail and see what it says",
   3765           expects=("error-screen", "internal-error-code", "core-internal",
   3766                    "silent-failure", "blank-screen"))
   3767 def s_api_error_sweep(c: Ctx) -> None:
   3768     """One injected failure per screen.
   3769 
   3770     Every one of these is a reply the app can get in the field -- a request
   3771     that times out, an exchange that is down, a database that is busy -- and
   3772     each screen either says so or says nothing.  The oracles decide; this
   3773     scenario only has to get each screen to make its call while the error is
   3774     queued.
   3775     """
   3776     cases = [
   3777         ("getBalances", lambda: c.back_to_home()),
   3778         ("getTransactionsV2", lambda: open_transactions(c)),
   3779         ("listExchanges", lambda: open_exchange_list(c)),
   3780         ("getContacts", lambda: (c.app.open_settings(),
   3781                                  c.app.scroll_to_text(r"(?i)^Contacts$"),
   3782                                  c.must_tap(r"(?i)^Contacts$"))),
   3783         ("listBankAccounts", lambda: (c.app.open_settings(),
   3784                                       c.app.scroll_to_text(r"(?i)^Bank accounts$"),
   3785                                       c.must_tap(r"(?i)^Bank accounts$"))),
   3786         ("getDepositWireTypes", lambda: (c.back_to_home(),
   3787                                          c.must_tap(r"(?i)^Deposit$", timeout=20))),
   3788         ("getWithdrawalDetailsForAmount",
   3789          lambda: (c.back_to_home(), c.must_tap(r"(?i)^Withdraw$", timeout=20))),
   3790         ("getMaxPeerPushDebitAmount",
   3791          lambda: (c.back_to_home(), c.must_tap(r"(?i)^Send$", timeout=20))),
   3792         ("listDiscounts", lambda: (c.back_to_home(),
   3793                                    c.app.scroll_to_text(r"(?i)^Discounts$"),
   3794                                    c.must_tap(r"(?i)^Discounts$"))),
   3795         ("getDonau", lambda: (c.app.open_settings(),
   3796                               c.app.scroll_to_text(r"(?i)^Tax-deductible donations$"),
   3797                               c.must_tap(r"(?i)^Tax-deductible donations$"))),
   3798         ("getCurrencySpecification", lambda: c.back_to_home()),
   3799         ("getExchangeTos", lambda: (open_exchange_list(c),
   3800                                     exchange_menu(c),
   3801                                     c.must_tap(r"(?i)terms of service", timeout=15))),
   3802         ("getMaxDepositAmount", lambda: (c.back_to_home(),
   3803                                          c.must_tap(r"(?i)^Deposit$", timeout=20))),
   3804         ("listSubscriptions", lambda: (c.back_to_home(),
   3805                                        c.app.scroll_to_text(r"(?i)^Passes$"),
   3806                                        c.must_tap(r"(?i)^Passes$"))),
   3807     ]
   3808     # The shipped wallet-core may be older than the experiment: a wallet-core
   3809     # that does not know "api-error" treats the URI as an unknown experiment
   3810     # and the whole sweep would measure nothing.
   3811     c.dev.logcat(clear=True)
   3812     c.app.handle_uri(api_error_uri("getBalances", count=1))
   3813     time.sleep(3)
   3814     log = c.dev.logcat(lines=400)
   3815     if "unknown" in log.lower() and "experiment" in log.lower():
   3816         bad = [l for l in log.splitlines() if "experiment" in l.lower()][:2]
   3817         c.note("this wallet-core does not support api-error: " + " / ".join(bad)[:240])
   3818         return
   3819     c.note("api-error is accepted by this wallet-core")
   3820 
   3821     for operation, visit in cases:
   3822         c.back_to_home()
   3823         c.dev.logcat(clear=True)
   3824         c.app.handle_uri(api_error_uri(operation))
   3825         time.sleep(2)
   3826         # Applying an experiment ends with a back navigation, which closes the
   3827         # app when the URI is what started it; without this the next case
   3828         # measures the launcher instead of a wallet screen.
   3829         for attempt in range(3):
   3830             if c.dev.dump().activity.startswith(PKG):
   3831                 break
   3832             c.note(f"{operation}: the app left the foreground; relaunching")
   3833             c.dev.launch()
   3834             time.sleep(6)
   3835         else:
   3836             c.note(f"{operation}: could not get the app back; skipping")
   3837             continue
   3838         try:
   3839             c.app.home()
   3840             visit()
   3841         except (TimeoutError, RuntimeError) as e:
   3842             c.note(f"{operation}: could not reach its screen ({str(e)[:120]})")
   3843             continue
   3844         time.sleep(4)
   3845         screen = c.dev.dump()
   3846         said = screen.find(r"(?i)error|failed|could not|unavailable|try again|"
   3847                            r"something went wrong") is not None
   3848         c.note(f"{operation}: shows an error: {said}; "
   3849                + str(screen.texts()[:12]))
   3850         if not said:
   3851             c.note(f"WARNING: {operation} failed and the screen says nothing")
   3852         c.check()
   3853     # Leave no injected errors behind for the next scenario.
   3854     c.app.handle_uri("taler+http://dev-experiment/clear-api-errors")
   3855     c.ep.check_database()
   3856 
   3857 
   3858 @scenario("contacts_add_and_forget", setup="funded",
   3859           about="add a contact by hand, then delete it")
   3860 def s_contacts_add(c: Ctx) -> None:
   3861     """`addContact` and `deleteContact` have never run.
   3862 
   3863     The contact list's own dialog is the only way to them that does not go
   3864     through the directory service, and its OK button stays disabled until the
   3865     petname, the alias and the mailbox are all filled.
   3866     """
   3867     c.app.open_settings()
   3868     c.app.scroll_to_text(r"(?i)^Contacts$")
   3869     c.must_tap(r"(?i)^Contacts$", timeout=20)
   3870     c.require(r"(?i)Contacts|No contacts yet|Add Contact", timeout=25)
   3871     c.check()
   3872     if not c.tap(r"(?i)^Add Contact$", timeout=20):
   3873         c.note("no way to add a contact")
   3874         return
   3875     screen = c.require(r"(?i)Petname|Alias|Mailbox", timeout=20)
   3876     c.note("add-contact dialog: " + str(screen.texts()[:12]))
   3877     fields = screen.editable()
   3878     c.note(f"{len(fields)} fields in the dialog")
   3879     if len(fields) < 3:
   3880         c.note("the dialog does not have the fields it is supposed to")
   3881         return
   3882     c.fill("Simulator Friend", 0)
   3883     c.fill("friend@example.com", 1)
   3884     c.fill("http://localhost:8081/mailbox/ABCD1234", len(fields) - 1)
   3885     time.sleep(1)
   3886     added = c.tap_button(r"(?i)^OK$|^Add$", timeout=15)
   3887     time.sleep(3)
   3888     listed = c.dev.dump()
   3889     c.note(f"after adding (OK tappable: {added}): " + str(listed.texts()[:12]))
   3890     if listed.find(r"(?i)Simulator Friend|friend@example.com") is None:
   3891         c.note("WARNING: the contact does not appear in the list")
   3892     c.check()
   3893     # And away again: long-press or a menu, whichever the list offers.
   3894     row = listed.find(r"(?i)Simulator Friend")
   3895     if row is not None:
   3896         c.dev.long_press(row)
   3897         time.sleep(2)
   3898         c.note("after a long press: " + str(c.dev.dump().texts()[:12]))
   3899         c.tap(r"(?i)^Delete$|^Forget$|^Remove$", timeout=8)
   3900         time.sleep(2)
   3901         c.tap(r"(?i)^OK$|^Yes$|^Delete$", timeout=8)
   3902         time.sleep(2)
   3903         c.note("after deleting: " + str(c.dev.dump().texts()[:12]))
   3904     c.check()
   3905     c.ep.check_database()
   3906 
   3907 
   3908 def api_response_uri(operation: str, response: dict, count: int = 5) -> str:
   3909     """A canned reply for a wallet-core operation, base64url JSON."""
   3910     import base64
   3911     blob = base64.urlsafe_b64encode(
   3912         json.dumps(response).encode()).decode().rstrip("=")
   3913     return (f"taler+http://dev-experiment/api-response?operation={operation}"
   3914             f"&response={blob}&count={count}")
   3915 
   3916 
   3917 def _balance(currency: str, url: str, available: str) -> dict:
   3918     return {
   3919         "scopeInfo": {"type": "exchange", "currency": currency, "url": url},
   3920         "available": available,
   3921         "pendingIncoming": f"{currency}:0",
   3922         "pendingOutgoing": f"{currency}:0",
   3923         "disablePeerPayments": False,
   3924     }
   3925 
   3926 
   3927 @scenario("api_response_hostile", setup="funded",
   3928           about="feed the balance screen replies it would never see in a test",
   3929           expects=("error-screen", "internal-error-screen", "internal-error-code",
   3930                    "core-internal", "glued-currency", "blank-screen",
   3931                    "mixed-amount-notation"))
   3932 def s_api_response_hostile(c: Ctx) -> None:
   3933     """Well-formed replies with hostile *values*.
   3934 
   3935     An amount larger than the wallet's own maximum, a currency name longer
   3936     than any symbol, and a dozen scopes at once are all things a real
   3937     deployment can produce, and none of them can be produced by this stack.
   3938     """
   3939     cases = {
   3940         "huge amount": {"balances": [
   3941             _balance("EUR", LOCAL_EXCHANGE, "EUR:999999999999.99")]},
   3942         "long currency name": {"balances": [
   3943             _balance("VERYLONGCURRENCY", LOCAL_EXCHANGE, "VERYLONGCURRENCY:1.00")]},
   3944         "twelve scopes": {"balances": [
   3945             _balance("EUR", f"http://localhost:80{80 + i}/", f"EUR:{i + 1}.00")
   3946             for i in range(12)]},
   3947         "zero everywhere": {"balances": [
   3948             _balance("EUR", LOCAL_EXCHANGE, "EUR:0")]},
   3949     }
   3950     for name, response in cases.items():
   3951         c.back_to_home()
   3952         c.dev.logcat(clear=True)
   3953         # The queue is FIFO and holds `count` copies, so leftovers from the
   3954         # previous case would be what the next one measures.
   3955         c.app.handle_uri("taler+http://dev-experiment/clear-api-responses")
   3956         time.sleep(1.5)
   3957         if not c.dev.dump().activity.startswith(PKG):
   3958             c.dev.launch()
   3959             time.sleep(5)
   3960         c.app.handle_uri(api_response_uri("getBalances", response, count=2))
   3961         time.sleep(2)
   3962         if not c.dev.dump().activity.startswith(PKG):
   3963             c.dev.launch()
   3964             time.sleep(5)
   3965         # The main screen asks for balances whenever it is shown.
   3966         c.back_to_home()
   3967         time.sleep(4)
   3968         screen = c.dev.dump()
   3969         c.note(f"{name}: " + str(screen.texts()[:16]))
   3970         c.check()
   3971         # More than one scope gives the pager a list page as well, which is
   3972         # the only thing that renders BalancesListComposable.
   3973         if name == "twelve scopes":
   3974             w, h = c.dev.size()
   3975             for _ in range(3):
   3976                 c.dev.shell(f"input swipe {int(w * 0.85)} {int(h * 0.45)} "
   3977                             f"{int(w * 0.15)} {int(h * 0.45)} 400")
   3978                 time.sleep(1.5)
   3979             c.note("after paging: " + str(c.dev.dump().texts()[:16]))
   3980             c.check()
   3981     c.app.handle_uri("taler+http://dev-experiment/clear-api-responses")
   3982     c.ep.check_database()
   3983 
   3984 
   3985 @scenario("error_screen_without_dev_mode", setup="funded",
   3986           about="what a release build shows for an error with no hint",
   3987           expects=("error-screen", "internal-error-code", "core-internal",
   3988                    "blank-screen"))
   3989 def s_error_screen_release(c: Ctx) -> None:
   3990     """The error screen the campaign never sees.
   3991 
   3992     Everything here runs in developer mode, because `taler+http://` needs it,
   3993     and the error screen shows the raw JSON in that mode.  Without it the whole
   3994     explanation is `TalerErrorInfo.userFacingMsg`, which is the hint and the
   3995     message concatenated -- and nothing at all when the reply carries neither.
   3996     """
   3997     # Queue the failure first: the URI needs developer mode to be delivered.
   3998     # An error with neither hint nor message is what makes the release screen
   3999     # empty, so api_error_uri is asked for one without a hint.
   4000     c.back_to_home()
   4001     c.app.handle_uri(api_error_uri("getBalances", hint="", count=20))
   4002     time.sleep(2)
   4003     if not c.dev.dump().activity.startswith(PKG):
   4004         c.dev.launch()
   4005         time.sleep(5)
   4006     with_dev = c.dev.dump()
   4007     c.note("with developer mode: " + str(with_dev.texts()[:10]))
   4008     c.check()
   4009 
   4010     # Now turn developer mode off, which is what a release build is.
   4011     c.app.open_settings()
   4012     c.app.scroll_to_text(r"(?i)^Developer mode$")
   4013     screen = c.dev.dump()
   4014     row = screen.find(r"(?i)^Developer mode$")
   4015     if row is None:
   4016         c.note("no developer mode row")
   4017         return
   4018     _, y = row.center
   4019     width = max(n.bounds[2] for n in screen.nodes)
   4020     c.dev.tap(width - 100, y)
   4021     time.sleep(2)
   4022     c.note(f"developer mode now on: {c.app.dev_mode_on()}")
   4023     c.back_to_home()
   4024     time.sleep(4)
   4025     without_dev = c.dev.dump()
   4026     c.note("without developer mode: " + str(without_dev.texts()[:12]))
   4027     # "Error" and an export affordance, and nothing that says what happened.
   4028     explained = [t for t in without_dev.texts()
   4029                  if t.strip() not in ("Error", "Copy", "Share", "Settings",
   4030                                       "Internal event log", "Scan QR code",
   4031                                       "Wallet")
   4032                  and "Export error" not in t]
   4033     c.note(f"anything explaining the error: {explained[:6]}")
   4034     if not explained:
   4035         c.note("WARNING: the error screen explains nothing without developer mode")
   4036     c.check()
   4037     # taler+http:// is refused while developer mode is off, so the clearing URI
   4038     # needs it back first.
   4039     c.app.enable_dev_mode()
   4040     c.app.handle_uri("taler+http://dev-experiment/clear-api-errors")
   4041     c.ep.check_database()
   4042 
   4043 
   4044 @scenario("denom_loss_transaction", setup="funded",
   4045           about="a loss-of-funds transaction and its detail screen",
   4046           expects=("error-screen",))
   4047 def s_denom_loss(c: Ctx) -> None:
   4048     """`TransactionDenomLoss` has never been rendered.
   4049 
   4050     It appears when an exchange's denomination expires or is revoked while the
   4051     wallet still holds coins of it -- which no stack can produce on demand, but
   4052     wallet-core will insert one on request.
   4053     """
   4054     import dbprobe
   4055     c.back_to_home()
   4056     c.dev.logcat(clear=True)
   4057     c.app.handle_uri("taler+http://dev-experiment/insert-denom-loss")
   4058     time.sleep(3)
   4059     for _ in range(3):
   4060         if c.dev.dump().activity.startswith(PKG):
   4061             break
   4062         c.dev.launch()
   4063         time.sleep(6)
   4064     # Did wallet-core accept the experiment at all?  The shipped qtart may be
   4065     # older than it.
   4066     log = c.dev.logcat(lines=400)
   4067     complaints = [l for l in log.splitlines()
   4068                   if "experiment" in l.lower() and ("error" in l.lower()
   4069                                                     or "unknown" in l.lower())]
   4070     c.note("wallet-core on the experiment: " + (" / ".join(complaints[-2:])[:240]
   4071                                                 or "no complaint"))
   4072     db = dbprobe.pull(c.dev)
   4073     rows: list = []
   4074     try:
   4075         rows = dbprobe.rows(db, "select * from denom_loss_events", limit=5)
   4076         c.note(f"denom_loss_events rows: {len(rows)}")
   4077         for r in rows:
   4078             c.note("  " + str({k: str(v)[:40] for k, v in dict(r).items()})[:240])
   4079     except Exception as e:  # noqa: BLE001
   4080         c.note(f"could not read denom_loss_events: {str(e)[:120]}")
   4081     c.app.home()
   4082     time.sleep(3)
   4083     c.note("home after the loss event: " + str(c.dev.dump().texts()[:14]))
   4084     c.check()
   4085     screen = open_transactions(c)
   4086     c.note("recent transactions: " + str(screen.texts()[:18]))
   4087     loss = screen.find(r"(?i)Loss of funds")
   4088     if loss is None:
   4089         # The main screen's list belongs to the selected scope, and the event
   4090         # is in a currency of its own; "All" is the unscoped list.
   4091         if c.tap(r"(?i)^All$", timeout=10):
   4092             time.sleep(3)
   4093             screen = c.dev.dump()
   4094             c.note("all transactions: " + str(screen.texts()[:18]))
   4095             loss = screen.find(r"(?i)Loss of funds")
   4096     if loss is None:
   4097         # Not a defect, and worth saying so rather than leaving a WARNING that
   4098         # reads like one: the dev experiment inserts the event for TESTKUDOS
   4099         # (the row's own `currency` column says so), and a wallet holding only
   4100         # EUR has no TESTKUDOS scope for it to appear under.  Rendering
   4101         # TransactionDenomLoss would need a loss in a currency the wallet
   4102         # actually holds, which means a denomination expiring under it --
   4103         # not something this stack can arrange.
   4104         currencies = {dict(row).get("currency") for row in rows}
   4105         c.note(f"the loss event does not appear in any list, as expected: it is "
   4106                f"in {currencies or '(unknown)'} and this wallet holds EUR")
   4107         c.check()
   4108         return
   4109     c.dev.tap_node(loss, screen)
   4110     time.sleep(3)
   4111     detail = c.dev.dump()
   4112     c.note("loss detail: " + str(detail.texts()[:16]))
   4113     if detail.find(r"(?i)Amount lost|Reason|expired|revoked") is None:
   4114         c.note("WARNING: the loss detail screen shows none of its own labels")
   4115     c.check()
   4116     c.ep.check_database()
   4117 
   4118 
   4119 @scenario("exchange_turns_hostile", setup="funded",
   4120           about="the exchange's protocol version and master key change under the wallet",
   4121           expects=("error-screen", "internal-error-code", "core-internal",
   4122                    "background-error", "stuck-operation", "blank-screen"))
   4123 def s_exchange_turns_hostile(c: Ctx) -> None:
   4124     """Two events a wallet must survive and explain.
   4125 
   4126     An exchange that answers with a protocol version this wallet cannot speak
   4127     is unusable; an exchange whose master public key has changed is either
   4128     compromised or has been replaced, and the wallet holds coins signed by the
   4129     old one.  Neither can be produced by configuration -- wallet-core will
   4130     pretend, per exchange base URL, on request.
   4131     """
   4132     url = LOCAL_EXCHANGE
   4133     quoted = url.replace(":", "%3A").replace("/", "%2F")
   4134     cases = [
   4135         ("protocol version 999",
   4136          f"taler+http://dev-experiment/start-fakeprotover"
   4137          f"?base_url={quoted}&fake_ver=999%3A0%3A0&fup=1"),
   4138         ("a different master key",
   4139          f"taler+http://dev-experiment/start-fakemasterpub"
   4140          f"?base_url={quoted}"
   4141          f"&fake_pub=0000000000000000000000000000000000000000000000000000&fup=1"),
   4142     ]
   4143     for name, uri in cases:
   4144         c.back_to_home()
   4145         c.dev.logcat(clear=True)
   4146         c.app.handle_uri(uri)
   4147         time.sleep(4)
   4148         for _ in range(3):
   4149             if c.dev.dump().activity.startswith(PKG):
   4150                 break
   4151             c.dev.launch()
   4152             time.sleep(6)
   4153         c.app.home()
   4154         time.sleep(4)
   4155         c.note(f"{name}: home shows " + str(c.dev.dump().texts()[:14]))
   4156         c.check()
   4157         # The payment services screen is where the wallet would say so.
   4158         open_exchange_list(c)
   4159         time.sleep(3)
   4160         listed = c.dev.dump()
   4161         c.note(f"{name}: payment services show " + str(listed.texts()[:16]))
   4162         if listed.find(r"(?i)error|not supported|incompatible|too old|too new|"
   4163                        r"changed|unavailable") is None:
   4164             c.note(f"WARNING: nothing on the exchange list mentions {name}")
   4165         c.check()
   4166         # And a withdrawal, which is what the user would try next.
   4167         c.back_to_home()
   4168         if c.tap(r"(?i)^Withdraw$", timeout=20):
   4169             time.sleep(5)
   4170             prompt = c.dev.dump()
   4171             c.note(f"{name}: the withdraw screen shows " + str(prompt.texts()[:14]))
   4172             c.check()
   4173         log = c.dev.logcat(lines=500)
   4174         codes = sorted({m for m in re.findall(r'"code":\s*(\d{4})', log)})
   4175         c.note(f"{name}: error codes in the log: {codes[:8]}")
   4176 
   4177     # And the case that puts an error *on a transaction*: a withdrawal that is
   4178     # already pending when the exchange becomes unusable.  Nothing else in the
   4179     # suite has ever rendered `ErrorTransactionButton`.
   4180     c.app.fresh_start(dev_mode=True)
   4181     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
   4182     c.app.handle_uri(op["taler_withdraw_uri"])
   4183     c.accept_tos()
   4184     if not c.tap(r"(?i)confirm withdrawal", timeout=40):
   4185         c.note("could not start a withdrawal to break")
   4186         return
   4187     c.see(r"(?i)Waiting for authorization|Authorize in bank|transaction is pending",
   4188           timeout=60)
   4189     c.app.handle_uri(
   4190         f"taler+http://dev-experiment/start-fakemasterpub?base_url={quoted}"
   4191         f"&fake_pub=0000000000000000000000000000000000000000000000000000&fup=1")
   4192     time.sleep(3)
   4193     for _ in range(3):
   4194         if c.dev.dump().activity.startswith(PKG):
   4195             break
   4196         c.dev.launch()
   4197         time.sleep(6)
   4198     # Push the withdrawal along, so its next step fails.
   4199     c.bank.confirm_withdrawal(*flows.WALLET_USER, op["withdrawal_id"])
   4200     for _ in range(8):
   4201         time.sleep(5)
   4202         screen = c.dev.dump()
   4203         if screen.find(r"(?i)has failed|error|Show error") is not None:
   4204             break
   4205     c.note("the pending withdrawal now: " + str(c.dev.dump().texts()[:16]))
   4206     c.check()
   4207     open_transactions(c)
   4208     rows = transaction_rows(c.dev.dump())
   4209     if rows:
   4210         c.dev.tap_node(rows[0])
   4211         time.sleep(3)
   4212         detail = c.dev.dump()
   4213         c.note("its detail screen: " + str(detail.texts()[:16]))
   4214         if c.tap(r"(?i)Show error|^Error$", timeout=8):
   4215             time.sleep(2)
   4216             c.note("error block: " + str(c.dev.dump().texts()[:14]))
   4217         c.check()
   4218     c.ep.check_database()
   4219 
   4220 
   4221 @scenario("peer_push_abandon", setup="funded",
   4222           about="look for Abandon on an outgoing peer payment and on a deposit")
   4223 def s_peer_push_abandon(c: Ctx) -> None:
   4224     """Where `failTransaction` can be reached from, if anywhere.
   4225 
   4226     wallet-core puts `TransactionAction.Fail` in the action list for deposits
   4227     and for outgoing peer payments, so the withdrawal scenarios could never
   4228     reach it -- but an outgoing peer payment turns out to offer Retry, Abort
   4229     and Suspend while it is live, and Resume and Abort once suspended, with no
   4230     Abandon in sight.  This scenario records both, and then tries a deposit.
   4231     """
   4232     c.back_to_home()
   4233     before = c.app.balances()
   4234     c.note(f"balance before: {before}")
   4235     c.must_tap(r"(?i)^Send$", timeout=30)
   4236     c.require(r"(?i)Send money|Amount to send|Purpose", timeout=30)
   4237     c.set_amount("€5.00", "500")
   4238     c.must_tap(r"(?i)^Send ", timeout=30)
   4239     c.see(r"(?i)Scan this QR code to receive|copy and send this URI", timeout=60)
   4240     c.check()
   4241     # Nobody accepts it; the wallet's own way out is Abandon.  wallet-core
   4242     # offers it on an outgoing peer payment only once the transaction is
   4243     # suspended -- while it is live the choices are Suspend and Abort.
   4244     # The QR code is the top of the screen; the actions are below it.
   4245     try:
   4246         c.app.scroll_to_text(r"(?i)^Suspend$|^Abandon$|^Abort$", max_scrolls=5)
   4247     except TimeoutError:
   4248         c.note("no actions on the outgoing payment: "
   4249                + str(c.dev.dump().texts()[:16]))
   4250         return
   4251     c.note("live actions: " + str(c.dev.dump().texts()[:18]))
   4252     if not c.tap(r"(?i)^Abandon$", timeout=10):
   4253         if not c.tap(r"(?i)^Suspend$", timeout=15):
   4254             c.note("neither Abandon nor Suspend is offered")
   4255             return
   4256         time.sleep(4)
   4257         try:
   4258             c.app.scroll_to_text(r"(?i)^Abandon$|^Resume$", max_scrolls=5)
   4259         except TimeoutError:
   4260             pass
   4261         c.note("after suspending: " + str(c.dev.dump().texts()[:18]))
   4262         c.check()
   4263         if not c.tap(r"(?i)^Abandon$", timeout=15):
   4264             c.note("Abandon is not offered even once suspended: "
   4265                    + str(c.dev.dump().texts()[:18]))
   4266             # A deposit is the other place wallet-core offers it.
   4267             c.back_to_home()
   4268             if not c.tap(r"(?i)^Deposit$", timeout=20):
   4269                 return
   4270             screen = c.require(r"(?i)Deposit|bank account|Amount", timeout=25)
   4271             account = screen.find(r"(?i)^wallet\d+$") or screen.find(r"(?i)x-taler-bank")
   4272             if account is not None:
   4273                 c.dev.tap_node(account, screen)
   4274                 time.sleep(3)
   4275             if not c.set_amount("€1.00", "100"):
   4276                 c.note("could not set a deposit amount")
   4277                 return
   4278             if not c.tap(r"(?i)^Make deposit$|^Deposit$", timeout=20):
   4279                 c.note("could not make the deposit")
   4280                 return
   4281             time.sleep(4)
   4282             try:
   4283                 c.app.scroll_to_text(r"(?i)^Abandon$|^Suspend$|^Abort$",
   4284                                      max_scrolls=5)
   4285             except TimeoutError:
   4286                 pass
   4287             c.note("a deposit's actions: " + str(c.dev.dump().texts()[:18]))
   4288             if not c.tap(r"(?i)^Abandon$", timeout=10):
   4289                 # wallet-core offers Fail on a deposit that is *aborting*
   4290                 # (deposits.ts: Aborting, SuspendedAborting,
   4291                 # PendingAggregateKyc, …), so aborting one is the way in -- if
   4292                 # the aggregator has not already finalised it.
   4293                 if c.tap(r"(?i)^Abort$", timeout=10):
   4294                     time.sleep(4)
   4295                     c.note("after aborting the deposit: "
   4296                            + str(c.dev.dump().texts()[:18]))
   4297                     c.check()
   4298             if c.tap(r"(?i)^Abandon$", timeout=10):
   4299                 time.sleep(4)
   4300                 c.note("abandoned the deposit: " + str(c.dev.dump().texts()[:14]))
   4301                 c.check()
   4302             else:
   4303                 c.note("Abandon is offered in none of the deposit states this "
   4304                        "stack produces")
   4305             return
   4306     if c.see(r"(?i)Abandon transaction|Are you sure", timeout=10):
   4307         c.tap(r"(?i)^Abandon$|^OK$|^Yes$")
   4308     time.sleep(5)
   4309     after_screen = c.dev.dump()
   4310     c.note("after abandoning: " + str(after_screen.texts()[:14]))
   4311     c.check()
   4312     # The coins are refreshed back into the balance; that takes a moment.
   4313     for _ in range(10):
   4314         time.sleep(4)
   4315         c.back_to_home()
   4316         now = c.app.balances()
   4317         if now and now != before:
   4318             break
   4319     c.note(f"balance after: {c.app.balances()} (was {before})")
   4320     c.check()
   4321     c.ep.check_database()
   4322 
   4323 
   4324 @scenario("history_after_forgetting_exchange", setup="funded",
   4325           about="forget the payment service and look for the transactions again")
   4326 def s_history_after_forget(c: Ctx) -> None:
   4327     """Every transaction list is scope-filtered.
   4328 
   4329     `TransactionManager.getTransactions` always passes a `scopeInfo`, and the
   4330     scopes come from the balances, so a currency with no balance scope has no
   4331     list to appear in.  Forgetting the only payment service is the ordinary way
   4332     to reach that state.
   4333     """
   4334     c.back_to_home()
   4335     before = transaction_rows(open_transactions(c))
   4336     c.note(f"transactions before: {[n.label[:24] for n in before]}")
   4337     c.check()
   4338     open_exchange_list(c)
   4339     if not exchange_menu(c):
   4340         c.note("no exchange menu")
   4341         return
   4342     c.note("menu: " + str(c.dev.dump().texts()[:14]))
   4343     if not c.tap(r"(?i)^Delete payment service$|^Forget payment service$|"
   4344                  r"^Forget$|^Delete$", timeout=15):
   4345         c.note("no way to forget the payment service")
   4346         return
   4347     time.sleep(2)
   4348     dialog = c.dev.dump()
   4349     c.note("the delete dialog: " + str(dialog.texts()[:10]))
   4350     # The wallet holds coins on this exchange, so a plain delete is refused;
   4351     # the dialog's own checkbox is what forces it.
   4352     if dialog.find(r"(?i)Force deletion") is not None:
   4353         c.tap(r"(?i)Force deletion")
   4354         time.sleep(1)
   4355     c.tap_button(r"(?i)^Delete$|^Forget$|^OK$|^Yes$", timeout=10)
   4356     time.sleep(6)
   4357     c.note("after forgetting: " + str(c.dev.dump().texts()[:14]))
   4358     c.check()
   4359     c.back_to_home()
   4360     time.sleep(3)
   4361     home = c.dev.dump()
   4362     c.note("home afterwards: " + str(home.texts()[:16]))
   4363     after = transaction_rows(c.dev.dump())
   4364     c.note(f"transactions after: {[n.label[:24] for n in after]}")
   4365     if before and not after:
   4366         c.note("WARNING: forgetting the payment service took the history with "
   4367                "it; the record of what was done with the money is gone")
   4368     c.check()
   4369     c.ep.check_database()
   4370 
   4371 
   4372 def _fake_withdrawal(txid: str, major: str, minor: str | None,
   4373                      actions: list[str], error: dict | None = None) -> dict:
   4374     """A withdrawal transaction as wallet-core would report it."""
   4375     tx: dict = {
   4376         "type": "withdrawal",
   4377         "transactionId": f"txn:withdrawal:{txid}",
   4378         "timestamp": {"t_s": int(time.time())},
   4379         "txState": {"major": major, **({"minor": minor} if minor else {})},
   4380         "txActions": actions,
   4381         "amountRaw": "EUR:10",
   4382         "amountEffective": "EUR:9.87",
   4383         "scopes": [{"type": "exchange", "currency": "EUR",
   4384                     "url": LOCAL_EXCHANGE}],
   4385         "exchangeBaseUrl": LOCAL_EXCHANGE,
   4386         "withdrawalDetails": {"type": "manual-transfer",
   4387                               "reserveClosingDelay": {"d_us": 3600000000}},
   4388     }
   4389     if error is not None:
   4390         tx["error"] = error
   4391     return tx
   4392 
   4393 
   4394 @scenario("nfc_tap_to_pay", setup="funded",
   4395           about="a payment arriving over NFC, as a tapped tag delivers it",
   4396           expects=("error-screen", "background-error", "stuck-operation"))
   4397 def s_nfc_tap_to_pay(c: Ctx) -> None:
   4398     """The tap-to-pay entry point, which nothing had ever used.
   4399 
   4400     `MainActivity` has three external entry points -- a VIEW intent, shared
   4401     text, and `NfcAdapter.ACTION_NDEF_DISCOVERED` -- and only the first two had
   4402     ever been driven, although the sim build ships a `SEND_NDEF` hook built for
   4403     exactly this (the URI travels in a Parcelable `NdefMessage`, which `am
   4404     start` cannot construct).  The handler's own comment calls the NDEF-record
   4405     path a fallback for when the system leaves `intent.data` unset, and that is
   4406     the branch the hook exercises.
   4407     """
   4408     order = c.merchant.create_order("EUR:1", summary="Tapped order")
   4409     c.dev.send_ndef(order["pay_uri"])
   4410     screen = c.see(r"(?i)^Pay\b|Review order|Total:|Purchase", timeout=60)
   4411     if screen is None:
   4412         c.note("an NDEF tap did not open the payment prompt: "
   4413                + str(c.dev.dump().texts()[:14]))
   4414         c.check()
   4415         return
   4416     c.note("the tapped payment prompt: " + str(screen.texts()[:14]))
   4417     c.check()
   4418     c.tap_button(r"(?i)^Pay\b|confirm payment", timeout=30)
   4419     deadline = time.monotonic() + 90
   4420     paid = False
   4421     while time.monotonic() < deadline:
   4422         if c.merchant.order_status(order["order_id"],
   4423                                    order["token"]).get("order_status") == "paid":
   4424             paid = True
   4425             break
   4426         time.sleep(2)
   4427     c.note(f"the tapped order was paid: {paid}")
   4428     if not paid:
   4429         raise RuntimeError("a payment delivered over NFC was never paid")
   4430     c.check()
   4431 
   4432     # And the hostile taps: a tag carrying something that is not a Taler URI at
   4433     # all, and one carrying a Taler URI for an order that does not exist.
   4434     for label, uri in (
   4435         ("a plain website", "https://example.org/not-taler"),
   4436         ("a nonsense scheme", "taler+http://pay/"),
   4437         ("an order that does not exist",
   4438          f"taler+http://pay/{corpus.EXCHANGE}/{corpus.FAKE_ID}/"),
   4439     ):
   4440         c.back_to_home()
   4441         c.dev.send_ndef(uri)
   4442         time.sleep(4)
   4443         c.note(f"tapped {label}: " + str(c.dev.dump().texts()[:10]))
   4444         c.check()
   4445     c.ep.check_database()
   4446 
   4447 
   4448 @scenario("transaction_details_by_type", setup="funded",
   4449           about="open the detail screen of every transaction type the stack "
   4450                 "can produce",
   4451           expects=("error-screen", "unfinished-transaction",
   4452                    "mixed-amount-notation", "glued-currency"))
   4453 def s_transaction_details_by_type(c: Ctx) -> None:
   4454     """One detail screen per transaction kind.
   4455 
   4456     `TransactionDetailScreen` branches on the transaction's type -- withdrawal,
   4457     payment, refund, deposit, peer push/pull debit/credit, denomination loss --
   4458     and each branch has its own composable.  Scenarios create those
   4459     transactions all the time but almost never open them, which is why the
   4460     detail screen sits at 56 % and several per-type composables at 0 %.
   4461 
   4462     Each counterparty step is allowed to fail on its own: what matters is that
   4463     whatever did end up in the list gets opened.
   4464     """
   4465     made: list[str] = []
   4466     steps = (
   4467         ("payment", lambda: flows.pay(c.app, c.merchant, "EUR:2",
   4468                                       "Detail-screen order")),
   4469         ("deposit", lambda: flows.deposit_to_bank(c.app, c.env, "100")),
   4470         ("peer push credit", lambda: flows.peer_receive(c.app, c.env, "EUR:1",
   4471                                                         c.cli)),
   4472         ("peer pull debit", lambda: flows.peer_pay_invoice(c.app, c.env,
   4473                                                            "EUR:1", c.cli)),
   4474     )
   4475     for name, step in steps:
   4476         try:
   4477             step()
   4478             made.append(name)
   4479         except Exception as e:  # noqa: BLE001
   4480             c.note(f"could not make a {name}: {str(e)[:140]}")
   4481         c.back_to_home()
   4482     c.note(f"transaction types created: {made}")
   4483     c.check()
   4484 
   4485     # Now the point of the scenario: open every row there is.  The list lives
   4486     # on the main screen under "Recent transactions", which is what
   4487     # transaction_rows understands; tapping the "All" chip navigates to the
   4488     # dedicated screen instead, where that header does not exist and every row
   4489     # went missing.
   4490     screen = open_transactions(c)
   4491     rows = transaction_rows(screen)
   4492     c.note(f"{len(rows)} transactions listed: "
   4493            + str([n.label[:26] for n in rows]))
   4494     opened = 0
   4495     for index in range(len(rows)):
   4496         # Re-read the list each time: going back recomposes it, and holding a
   4497         # node from an older dump taps whatever is at those coordinates now.
   4498         listing = open_transactions(c)
   4499         rows_now = transaction_rows(listing)
   4500         if index >= len(rows_now):
   4501             break
   4502         c.dev.tap_node(rows_now[index], listing)
   4503         time.sleep(2.5)
   4504         detail = c.dev.dump()
   4505         title = next((t for t in detail.texts()
   4506                       if re.search(r"(?i)transaction (is|was)|Received|Sent", t)),
   4507                      None)
   4508         c.note(f"detail {index}: {title!r} | "
   4509                + str([x for x in detail.texts()[:10]]))
   4510         c.check()
   4511         # The JSON dump and the error button are both developer-mode only and
   4512         # both on this screen.
   4513         if c.tap(r"(?i)^Show JSON$", timeout=6):
   4514             time.sleep(1.5)
   4515             c.check()
   4516             c.dev.back()
   4517             time.sleep(1)
   4518         if c.tap(r"(?i)^Error$", timeout=5):
   4519             time.sleep(1.5)
   4520             c.note(f"detail {index} carries an error: "
   4521                    + str(c.dev.dump().texts()[:8]))
   4522             c.check()
   4523             c.tap(r"(?i)^OK$|^Close$|^Cancel$", timeout=5)
   4524         # The overflow menu exists only for a transaction with a payto target
   4525         # -- a deposit or a manual withdrawal -- and holds one item, which is
   4526         # the only caller of copyToClipBoard on this screen.
   4527         if c.tap(r"(?i)^Menu$", timeout=4):
   4528             time.sleep(1)
   4529             menu = c.dev.dump()
   4530             c.note(f"detail {index} overflow menu: " + str(menu.texts()[:8]))
   4531             if c.tap(r"(?i)^Copy payto URI$", timeout=5):
   4532                 time.sleep(1)
   4533                 c.note(f"detail {index}: copied the payto URI")
   4534             else:
   4535                 c.dev.back()
   4536             c.check()
   4537         opened += 1
   4538         c.dev.back()
   4539         time.sleep(1.5)
   4540     c.note(f"opened {opened} detail screens")
   4541     c.check()
   4542     c.ep.check_database()
   4543 
   4544 
   4545 @scenario("transaction_states_rendered", setup="funded",
   4546           about="transaction states this stack cannot produce",
   4547           expects=("error-screen", "internal-error-screen", "internal-error-code",
   4548                    "core-internal", "blank-screen", "fee-on-dead-transaction"))
   4549 def s_transaction_states(c: Ctx) -> None:
   4550     """Every state the list has a branch for.
   4551 
   4552     `TransactionsComposable` renders differently for pending, aborting,
   4553     suspended, failed and unknown states, and for a transaction that carries
   4554     its own error; a stack produces two or three of those on a good day.  A
   4555     canned `getTransactionsV2` reply produces all of them, including a state
   4556     from the future -- the app keeps the unrecognised name on purpose, so what
   4557     it does with it is worth seeing.
   4558     """
   4559     transactions = [
   4560         _fake_withdrawal("AAAA1", "pending", "kyc", ["suspend", "abort"]),
   4561         _fake_withdrawal("AAAA2", "aborting", "bank", ["fail"]),
   4562         _fake_withdrawal("AAAA3", "suspended", "exchange-wait-reserve",
   4563                          ["resume", "fail"]),
   4564         _fake_withdrawal("AAAA4", "failed", None, ["delete"],
   4565                          error={"code": 7003,
   4566                                 "hint": "the exchange could not be reached"}),
   4567         _fake_withdrawal("AAAA5", "done", None, ["delete"]),
   4568         # A state this version of the app has never heard of.
   4569         _fake_withdrawal("AAAA6", "transmogrified", "inside-out", ["delete"]),
   4570         # And two the app cannot *parse* at all, which is the only way to reach
   4571         # TransactionSerializer's catch branch and the DummyTransaction it
   4572         # falls back to: a type that does not exist, and a known type missing
   4573         # a field it needs.
   4574         {
   4575             "type": "interpretive-dance",
   4576             "transactionId": "txn:interpretive-dance:AAAA7",
   4577             "timestamp": {"t_s": int(time.time())},
   4578             "txState": {"major": "done"},
   4579             "txActions": ["delete"],
   4580         },
   4581         {
   4582             "type": "withdrawal",
   4583             "transactionId": "txn:withdrawal:AAAA8",
   4584             "timestamp": {"t_s": int(time.time())},
   4585             "txState": {"major": "done"},
   4586             "txActions": ["delete"],
   4587             # no amountRaw/amountEffective/scopes: required, so this throws
   4588         },
   4589     ]
   4590     c.back_to_home()
   4591     c.app.handle_uri("taler+http://dev-experiment/clear-api-responses")
   4592     time.sleep(1.5)
   4593     if not c.dev.dump().activity.startswith(PKG):
   4594         c.dev.launch()
   4595         time.sleep(5)
   4596     c.app.handle_uri(api_response_uri("getTransactionsV2",
   4597                                       {"transactions": transactions}, count=8))
   4598     time.sleep(2)
   4599     for _ in range(3):
   4600         if c.dev.dump().activity.startswith(PKG):
   4601             break
   4602         c.dev.launch()
   4603         time.sleep(6)
   4604     c.app.home()
   4605     time.sleep(4)
   4606     screen = open_transactions(c)
   4607     c.note("the list: " + str(screen.texts()[:24]))
   4608     c.check()
   4609     if c.tap(r"(?i)^All$", timeout=10):
   4610         time.sleep(3)
   4611         full = c.dev.dump()
   4612         c.note("the full list: " + str(full.texts()[:28]))
   4613         c.check()
   4614         rows = transaction_rows(full)
   4615         c.note(f"{len(rows)} rows: {[n.label[:20] for n in rows][:8]}")
   4616         # The two unparseable transactions become DummyTransactions, which
   4617         # carry an error and no amount; the list should still render, and
   4618         # whatever it shows for them is worth reading.
   4619         if full.find(r"(?i)interpretive|UNKNOWN|Error") is not None:
   4620             c.note("the unparseable transactions show as: "
   4621                    + str([x for x in full.texts()
   4622                           if re.search(r"(?i)unknown|error|interpretive", x)][:4]))
   4623         else:
   4624             c.note("nothing on screen marks the two unparseable transactions")
   4625     # The failed one carries an error, which is the only way to render
   4626     # ErrorTransactionButton; its detail screen needs its own canned reply.
   4627     c.app.handle_uri(api_response_uri(
   4628         "getTransactionById",
   4629         _fake_withdrawal("AAAA4", "failed", None, ["delete"],
   4630                          error={"code": 7003,
   4631                                 "hint": "the exchange could not be reached"}),
   4632         count=4))
   4633     time.sleep(2)
   4634     for _ in range(3):
   4635         if c.dev.dump().activity.startswith(PKG):
   4636             break
   4637         c.dev.launch()
   4638         time.sleep(6)
   4639     c.app.home()
   4640     rows = transaction_rows(open_transactions(c))
   4641     if rows:
   4642         c.dev.tap_node(rows[0])
   4643         time.sleep(4)
   4644         detail = c.dev.dump()
   4645         c.note("a detail screen: " + str(detail.texts()[:20]))
   4646         if c.tap(r"(?i)Show error|^Error$", timeout=8):
   4647             time.sleep(2)
   4648             c.note("the error block: " + str(c.dev.dump().texts()[:16]))
   4649         c.check()
   4650     c.app.handle_uri("taler+http://dev-experiment/clear-api-responses")
   4651     c.ep.check_database()
   4652 
   4653 
   4654 TALDIR_CHALLENGES = "/opt/taldir/challenges.log"
   4655 
   4656 
   4657 def taldir_ready(c: Ctx) -> bool:
   4658     """Whether this worker can reach the directory the app hard-codes.
   4659 
   4660     The app always talks to https://taldir.gnunet.org, so the device has to
   4661     answer for that name: emu/tls-names.sh adds the hosts entry and forwards
   4662     the device's port 443 to the TLS front end, whose CA the sim build type
   4663     trusts.  Without that the scenario would only measure the refusal.
   4664     """
   4665     if "tcp:443" not in c.dev.adb("reverse", "--list", check=False):
   4666         c.note("port 443 is not mapped on this worker; run emu/tls-names.sh")
   4667         return False
   4668     try:
   4669         import socket
   4670         import ssl
   4671         # The front end's certificate is for the two hostnames and nothing
   4672         # else, so the probe has to validate the name the *device* validates
   4673         # while connecting to the address the device's port 443 forwards to.
   4674         # Asking for https://127.0.0.1:8443 instead fails with "IP address
   4675         # mismatch" and says nothing about whether the front end works.
   4676         ctx = ssl.create_default_context(cafile="/opt/taler-sim/tls/ca.crt")
   4677         with socket.create_connection(("127.0.0.1", 8443), timeout=5) as raw:
   4678             with ctx.wrap_socket(raw, server_hostname="taldir.gnunet.org") as tls:
   4679                 tls.sendall(b"GET /config HTTP/1.1\r\n"
   4680                             b"Host: taldir.gnunet.org\r\n"
   4681                             b"Connection: close\r\n\r\n")
   4682                 head = tls.recv(64)
   4683         if b" 200 " not in head:
   4684             raise RuntimeError(f"answered {head[:40]!r}")
   4685     except Exception as e:  # noqa: BLE001
   4686         c.note(f"the TLS front end is not answering: {str(e)[:120]}")
   4687         return False
   4688     return True
   4689 
   4690 
   4691 def latest_challenge(alias: str) -> Optional[str]:
   4692     """The challenge the directory's validator recorded for this alias."""
   4693     try:
   4694         with open(TALDIR_CHALLENGES) as f:
   4695             lines = [l.strip().split("\t") for l in f if alias in l]
   4696     except OSError:
   4697         return None
   4698     return lines[-1][2] if lines and len(lines[-1]) >= 3 else None
   4699 
   4700 
   4701 @scenario("alias_registration_real", setup="funded",
   4702           about="register an alias with a real directory, challenge and all",
   4703           expects=("error-screen", "internal-error-code", "core-internal"))
   4704 def s_alias_registration_real(c: Ctx) -> None:
   4705     """The whole alias registration, against a deployed taldir.
   4706 
   4707     Everything past the "Register Alias" button has never run: the app's URL
   4708     is a literal, so without the device answering for that name there is
   4709     nothing behind it.  With the directory deployed and the name resolved, the
   4710     flow is register -> challenge -> complete -> look up, and the challenge
   4711     comes from the validator's log the way it would come from an email.
   4712     """
   4713     if not taldir_ready(c):
   4714         return
   4715     alias = f"sim-w{WORKER}-{int(time.time())}@example.com"
   4716     c.app.open_settings()
   4717     c.app.scroll_to_text(r"(?i)^Alias Registration$", max_scrolls=12)
   4718     c.must_tap(r"(?i)^Alias Registration$")
   4719     screen = c.require(r"(?i)Alias|Duration|Register", timeout=25)
   4720     c.note("the form: " + str(screen.texts()[:12]))
   4721     c.check()
   4722     # Field 0 is the alias *type*, a read-only dropdown: tapping it opens the
   4723     # menu, typing goes nowhere, the alias stays empty -- which disables the
   4724     # register button -- and the open menu covers it.  The alias is field 1.
   4725     if not c.fill(alias, 1, clear=True):
   4726         c.note("no alias field")
   4727         return
   4728     time.sleep(1)
   4729     if not c.tap_button(r"(?i)^Register Alias$", timeout=15):
   4730         c.note("the register button would not tap; the form reads "
   4731                + str(c.dev.dump().texts()[:12]))
   4732         return
   4733     # The directory has to answer, and the validator has to run, before the
   4734     # challenge exists.
   4735     challenge = None
   4736     for _ in range(12):
   4737         time.sleep(3)
   4738         challenge = latest_challenge(alias)
   4739         if challenge:
   4740             break
   4741     after = c.dev.dump()
   4742     c.note(f"after registering (challenge: {challenge}): " + str(after.texts()[:14]))
   4743     c.check()
   4744     if challenge is None:
   4745         c.note("WARNING: the directory recorded no challenge for this alias")
   4746         return
   4747     # The screen should now be asking for it, in a field labelled "Challenge
   4748     # Solution", with an OK button under it.
   4749     waiting = c.dev.dump()
   4750     if waiting.find(r"(?i)Challenge Solution") is None:
   4751         c.note("the screen is not asking for the challenge: "
   4752                + str(waiting.texts()[:16]))
   4753         return
   4754     fields = [n for n in waiting.editable()]
   4755     if not fields:
   4756         c.note("no field to type the challenge into")
   4757         return
   4758     # The alias and duration fields are still above it; the solution field is
   4759     # the last one.
   4760     if not c.fill(challenge, len(fields) - 1, clear=True):
   4761         c.note("could not type the challenge")
   4762         return
   4763     time.sleep(1)
   4764     c.tap_button(r"(?i)^OK$", timeout=15)
   4765     time.sleep(6)
   4766     done = c.dev.dump()
   4767     c.note("after completing: " + str(done.texts()[:16]))
   4768     c.check()
   4769     # And the other half: look the alias up from the contacts screen.
   4770     c.app.open_settings()
   4771     c.app.scroll_to_text(r"(?i)^Contacts$", max_scrolls=12)
   4772     c.must_tap(r"(?i)^Contacts$")
   4773     if c.tap(r"(?i)^Add Contact$", timeout=20):
   4774         screen = c.require(r"(?i)Petname|Alias|Mailbox", timeout=20)
   4775         c.fill("Looked up", 0)
   4776         c.fill(alias, 1)
   4777         time.sleep(1)
   4778         if c.tap_button(r"(?i)Lookup with Taldir", timeout=15):
   4779             time.sleep(8)
   4780             c.note("after the lookup: " + str(c.dev.dump().texts()[:16]))
   4781             c.check()
   4782     c.ep.check_database()
   4783 
   4784 
   4785 @scenario("db_corruption", setup="funded",
   4786           about="scribble on the wallet database and restart the app",
   4787           # A corrupt database is supposed to fail to open; what is being
   4788           # checked is that the app explains it instead of crashing.
   4789           expects=("internal-error-screen", "core-internal", "internal-error-code"))
   4790 def s_db_corruption(c: Ctx) -> None:
   4791     """A corrupt database must produce an explained failure, not a crash.
   4792 
   4793     `WalletInitErrorScreen` exists for exactly this and has never been reached
   4794     by any other scenario.
   4795     """
   4796     from device import PKG
   4797     before = c.dev.shell(f"run-as {PKG} ls -l files/talerwalletdb.sqlite3", check=False)
   4798     c.note(f"database before: {before.strip()[:120]}")
   4799     c.dev.stop()
   4800     time.sleep(2)
   4801     # Overwrite the SQLite header in place; the file keeps its size, so this is
   4802     # corruption rather than truncation.
   4803     cmd = ("dd if=/dev/urandom of=files/talerwalletdb.sqlite3 "
   4804            "bs=512 count=2 conv=notrunc")
   4805     out = c.dev.shell(f"run-as {PKG} {cmd}", check=False)
   4806     c.note(f"corrupting: {out.strip()[:160]}")
   4807     c.dev.launch()
   4808     time.sleep(8)
   4809     screen = c.dev.dump()
   4810     c.note("after relaunch: " + str(screen.texts()[:14]))
   4811     c.check()
   4812     log = c.dev.logcat()
   4813     crashed = "FATAL EXCEPTION" in log
   4814     c.note(f"crashed: {crashed}")
   4815     if crashed:
   4816         c.ep.session.add([oracles.Finding(
   4817             "crash", "the app crashed after its database was corrupted",
   4818             "\n".join(l for l in log.splitlines() if "FATAL" in l)[:1000])])
   4819     # Whatever it shows, the wallet has to be usable again afterwards.
   4820     c.app.fresh_start(dev_mode=True)
   4821     c.note("after a wipe: " + str(c.dev.dump().texts()[:8]))
   4822     c.check()
   4823 
   4824 
   4825 @scenario("db_migration_prompt", setup="fresh",
   4826           about="plant a wallet database in the old format and migrate it")
   4827 def s_db_migration_prompt(c: Ctx) -> None:
   4828     """The database migration, which needs a database in the legacy format.
   4829 
   4830     wallet-core picks its backend from what the file already holds
   4831     (`host-impl.qtart.ts`: `inspectWalletDbFile`), so a file carrying
   4832     IndexedDB-emulation records is opened with the bridge and `init` reports
   4833     `IndexedDB`.  That is the only way to reach the "Upgrade wallet database"
   4834     row in the settings, `MainActivity`'s migration prompt and progress
   4835     dialog, `migrateDatabase`, and -- if the migration can be caught while it
   4836     runs -- `cancelProgressToken`, the last wallet-core operation no scenario
   4837     had exercised.
   4838 
   4839     The fixture in `corpus/legacy-indexeddb-wallet.db` has to come from the
   4840     *app's own* wallet-core, because IndexedDB refuses to open a database
   4841     newer than the schema version the opener asks for.  `taler-wallet-cli`
   4842     with `TALER_WALLET_DB_BACKEND=indexeddb` does write a legacy database, but
   4843     the checkout beside this one is 1.6.48, whose schema is version 36, while
   4844     the qtart the app embeds is 1.6.42 and asks for 34:
   4845 
   4846         VersionError: requested version 34, existing version is 36
   4847 
   4848     So the fixture is made by the app itself: build it with
   4849     `useNativeDb = false` in `MainViewModel`, launch it once, and copy
   4850     `files/talerwalletdb.sqlite3` back out.  That file carries
   4851     `taler-wallet-main-v10` at version 34, and has to be remade whenever the
   4852     bundled qtart moves its schema version.
   4853     """
   4854     from device import PKG
   4855     # The committed fixture is deliberately small.  A bigger one -- made the
   4856     # same way, by driving the useNativeDb=false build through a scenario
   4857     # first -- migrates slowly enough that the Cancel below can be caught, and
   4858     # is passed in with SIM_LEGACY_DB rather than carried in the repository.
   4859     legacy = Path(os.environ.get(
   4860         "SIM_LEGACY_DB",
   4861         Path(__file__).resolve().parent.parent / "corpus"
   4862         / "legacy-indexeddb-wallet.db"))
   4863     if not legacy.exists():
   4864         c.note(f"no legacy database at {legacy}; nothing to plant")
   4865         return
   4866 
   4867     c.dev.stop()
   4868     time.sleep(2)
   4869     c.dev.adb("push", str(legacy), "/data/local/tmp/legacy-wallet.db")
   4870     c.dev.shell("chmod 644 /data/local/tmp/legacy-wallet.db", check=False)
   4871     # The write-ahead log belongs to the database being replaced.
   4872     for leftover in ("talerwalletdb.sqlite3-wal", "talerwalletdb.sqlite3-shm"):
   4873         c.dev.shell(f"run-as {PKG} rm -f files/{leftover}", check=False)
   4874     # dd rather than a redirection: run-as execs its argument without a shell.
   4875     out = c.dev.shell(
   4876         f"run-as {PKG} dd if=/data/local/tmp/legacy-wallet.db "
   4877         "of=files/talerwalletdb.sqlite3", check=False)
   4878     c.note("planting the legacy database: " + out.strip()[:160])
   4879     planted = c.dev.shell(f"run-as {PKG} ls -l files/talerwalletdb.sqlite3",
   4880                           check=False)
   4881     c.note("database now: " + planted.strip()[:120])
   4882 
   4883     c.dev.launch()
   4884     time.sleep(10)
   4885     c.note("after relaunch: " + str(c.dev.dump().texts()[:14]))
   4886     c.check()
   4887 
   4888     # The row only exists when wallet-core reports the IndexedDB backend, so
   4889     # finding it is the proof that the planted file was accepted.
   4890     c.app.open_settings()
   4891     try:
   4892         c.app.scroll_to_text(r"(?i)^Upgrade wallet database$", max_scrolls=8)
   4893     except TimeoutError:
   4894         c.note("no migration row in the settings: wallet-core did not report "
   4895                "the IndexedDB backend for the planted database; "
   4896                + str(c.dev.dump().texts()[:16]))
   4897         c.check()
   4898         return
   4899     c.must_tap(r"(?i)^Upgrade wallet database$")
   4900     prompt = c.see(r"(?i)Upgrade wallet database\?", timeout=15)
   4901     if prompt is None:
   4902         c.note("the migration prompt did not open: "
   4903                + str(c.dev.dump().texts()[:14]))
   4904         c.check()
   4905         return
   4906     c.note("the prompt: " + str(prompt.texts()[:8]))
   4907     c.check()
   4908 
   4909     # "Later" first, so the deferral path is exercised too, then ask again.
   4910     if c.tap(r"(?i)^Later$", timeout=8):
   4911         time.sleep(2)
   4912         c.note("after Later: " + str(c.dev.dump().texts()[:10]))
   4913         c.check()
   4914         c.app.open_settings()
   4915         c.app.scroll_to_text(r"(?i)^Upgrade wallet database$", max_scrolls=8)
   4916         c.must_tap(r"(?i)^Upgrade wallet database$")
   4917         c.require(r"(?i)Upgrade wallet database\?", timeout=15)
   4918 
   4919     # Where the prompt's buttons are, so the progress dialog's Cancel can be
   4920     # tapped without a dump first: a dump costs about a second, which is
   4921     # longer than the whole migration on a database this size.
   4922     prompt_screen = c.dev.dump()
   4923     slots = [n.center for n in prompt_screen.labelled()
   4924              if re.match(r"(?i)^(Migrate now|Later)$", n.label.strip())]
   4925     # The Cancel on the progress dialog is the only caller of
   4926     # cancelProgressToken, and this harness cannot reach it.  Four attempts,
   4927     # all recorded in CAMPAIGN.md:
   4928     #
   4929     #   * a 57 KB legacy fixture -- migrates in well under a second;
   4930     #   * a 1.7 MB fixture with 512 records and 112 progress notifications --
   4931     #     the same;
   4932     #   * blind taps at the prompt's button coordinates, with no screen dump
   4933     #     in between (a dump alone costs about a second);
   4934     #   * freezing the process with SIGSTOP so the taps queue in the input
   4935     #     dispatcher, both before and after starting the migration.
   4936     #
   4937     # The taps below are the third of those, kept because they cost nothing
   4938     # and would start working the moment a fixture is large enough.  What
   4939     # would actually settle it is a legacy database of some thousands of
   4940     # records, or a debug hook that pauses the migration.
   4941     c.must_tap(r"(?i)^Migrate now$", timeout=15)
   4942     for x, y in slots:
   4943         c.dev.tap(x, y)
   4944 
   4945     # No separate dump before each attempt: every dump costs about a second,
   4946     # which is most of the window on a small database.
   4947     cancelled = False
   4948     for _ in range(15):
   4949         if c.tap(r"(?i)^Cancel$", timeout=1):
   4950             cancelled = True
   4951             c.note("cancelled the migration while it was running")
   4952             break
   4953     if cancelled:
   4954         # Cancelling is itself a state with its own dialog, and the operation
   4955         # it cancels is the only caller of cancelProgressToken.
   4956         if c.see(r"(?i)Cancelling", timeout=6) is not None:
   4957             c.note("the cancelling dialog was shown")
   4958     c.note(f"caught the migration in progress: {cancelled}")
   4959     time.sleep(8)
   4960     c.note("after the migration: " + str(c.dev.dump().texts()[:14]))
   4961     c.check()
   4962 
   4963     # Whichever way it went, the wallet has to be usable, and the backend it
   4964     # ends on has to be one of the two -- not a half-migrated database.
   4965     c.app.open_settings()
   4966     row = c.dev.dump().find(r"(?i)^Upgrade wallet database$")
   4967     c.note("the migration row is still offered: " + str(row is not None))
   4968     c.back_to_home()
   4969     c.check()
   4970     c.ep.check_database()
   4971 
   4972 
   4973 @scenario("donau_receipt", setup="funded",
   4974           about="pay for a tax receipt, then read the donation statement")
   4975 def s_donau_receipt(c: Ctx) -> None:
   4976     # The donau output type makes the merchant issue a tax receipt for the
   4977     # payment, which is what the statements screen lists.
   4978     order = c.merchant.create_v1_order(
   4979         [{"amount": "EUR:2", "description": "Donation with a receipt",
   4980           "inputs": [], "outputs": [{"type": "tax-receipt"}],
   4981           "max_fee": "EUR:0.5"}],
   4982         summary="Donation with a tax receipt",
   4983     )
   4984     c.app.handle_uri(order["pay_uri"])
   4985     screen = c.require(r"(?i)Review order|Total:|^Pay|donation|receipt", timeout=60)
   4986     c.note("donation prompt: " + str(screen.texts()[:14]))
   4987     c.check()
   4988     c.tap(r"(?i)^Pay\b|confirm payment", timeout=30)
   4989     time.sleep(6)
   4990     c.note("after paying: " + str(c.dev.dump().texts()[:12]))
   4991     c.back_to_home()
   4992     try:
   4993         c.app.scroll_to_text(r"(?i)^Donation statements$", max_scrolls=5)
   4994     except TimeoutError:
   4995         c.note("no donation statements section")
   4996         c.check()
   4997         return
   4998     c.must_tap(r"(?i)^Donation statements$")
   4999     # "Donation statements" is also the section header on the main screen, so
   5000     # the arrival has to be recognised by something only the statements screen
   5001     # has: its per-year list ("Donations 2026") or its own title.
   5002     screen = c.see(r"(?i)^Donations \d{4}$|^Donation statement$", timeout=25)
   5003     if screen is None:
   5004         # Expected, and now explained: the button is wired to
   5005         # onBalanceSelected(null) rather than to WalletDestination.DonauStatement,
   5006         # which has no caller at all -- see
   5007         # findings/donation-statements-button-is-wired-to-nothing.md.
   5008         c.note("the donation statements screen did not open (the button is a "
   5009                "no-op; donation-statements-button-is-wired-to-nothing.md): "
   5010                + str(c.dev.dump().texts()[:14]))
   5011         c.check()
   5012         return
   5013     c.note("statements: " + str(screen.texts()[:14]))
   5014     c.check()
   5015     rows = [n for n in screen.labelled()
   5016             if re.match(r"(?i)^Donations \d{4}$", n.label.strip())]
   5017     if rows:
   5018         c.dev.tap(*rows[0].center)
   5019         time.sleep(2)
   5020         detail = c.dev.dump()
   5021         c.note("statement detail: " + str(detail.texts()[:14]))
   5022         if detail.find(r"(?i)Show this QR code|Tax authority|Legal domain") is None:
   5023             c.note("WARNING: the statement detail shows none of its own labels")
   5024         c.check()
   5025     c.ep.check_database()
   5026 
   5027 
   5028 @scenario("refund_detail", setup="funded",
   5029           about="take a refund and open the refund transaction")
   5030 def s_refund_detail(c: Ctx) -> None:
   5031     order = flows.pay(c.app, c.merchant, "EUR:2", summary="Order to refund fully")
   5032     c.app.home()
   5033     res = c.merchant.refund(order["order_id"], "EUR:2", reason="simulator full refund")
   5034     uri = res.get("taler_refund_uri")
   5035     if not uri:
   5036         raise RuntimeError(f"merchant returned no refund uri: {res}")
   5037     c.app.handle_uri(uri)
   5038     time.sleep(5)
   5039     c.note("after the refund uri: " + str(c.dev.dump().texts()[:12]))
   5040     screen = open_transactions(c)
   5041     rows = transaction_rows(screen)
   5042     c.note(f"{len(rows)} transactions: {[n.label[:22] for n in rows]}")
   5043     for index in range(min(3, len(rows))):
   5044         screen = open_transactions(c)
   5045         rows_now = transaction_rows(screen)
   5046         if index >= len(rows_now):
   5047             break
   5048         c.dev.tap_node(rows_now[index], screen)
   5049         time.sleep(2)
   5050         detail = c.dev.dump()
   5051         if detail.find(r"(?i)refund"):
   5052             c.note("refund detail: " + str(detail.texts()[:12]))
   5053             c.check()
   5054             c.tap(r"(?i)^Show JSON$", timeout=8)
   5055             c.check()
   5056             c.dev.back()
   5057         c.dev.back()
   5058         time.sleep(1)
   5059     c.check()
   5060 
   5061 
   5062 @scenario("exchange_shopping", setup="funded",
   5063           about="the exchange's \"where to pay\" screen")
   5064 def s_exchange_shopping(c: Ctx) -> None:
   5065     """The "Where to pay" screen, which needs two exchanges to exist at all.
   5066 
   5067     The balance card that opens it is hidden while `shoppingUrls` is empty, and
   5068     with exactly one URL the button opens that site in a browser instead of the
   5069     screen -- so the screen is reachable only when the wallet holds a currency
   5070     from **two** exchanges that both advertise one (`SHOPPING_URL` in each
   5071     exchange's config).  The second exchange has to be in the balance, so this
   5072     withdraws from it first.
   5073     """
   5074     second = second_exchange_or_skip(c)
   5075     if second is not None:
   5076         # One URL is not enough: with a single entry the button opens that site
   5077         # in a browser.  Two take a *balance* at each exchange, so the second
   5078         # one has to be picked during a withdrawal rather than merely added.
   5079         # Coins at the second exchange, without touching any exchange-picking
   5080         # UI: the bank-integrated prompt has no service row (its exchange is
   5081         # fixed), and a manual withdrawal would need a real wire transfer.  A
   5082         # peer payment lands at the *sender's* exchange, so a peer funded at
   5083         # the second one gives this wallet a second EUR scope.
   5084         try:
   5085             # peer_receive knows both shapes of the terms prompt on this
   5086             # screen -- "Terms of Service" and "Review terms of service" --
   5087             # which is why this does not drive the accept by hand.
   5088             screen = flows.peer_receive(c.app, c.env, "EUR:2", c.cli,
   5089                                         exchange=second)
   5090             c.note("after receiving from the second service: "
   5091                    + str(screen.texts()[:12]))
   5092             time.sleep(8)
   5093         except Exception as e:  # noqa: BLE001
   5094             c.note(f"the second service did not reach the balance: {str(e)[:160]}")
   5095         c.check()
   5096         # What is left, for whoever picks this up: two services give two
   5097         # balance *scopes*, one pager page each, and the card on a page carries
   5098         # only that service's URL -- so each card still has one URL and the
   5099         # button opens a browser.  Merging them with "treat as global" (per the
   5100         # exchange menu) should put both on one card; driving that menu from
   5101         # here kept landing back on the home screen, and the screen is 62
   5102         # lines, so it was not worth more rounds of guessing.
   5103     c.back_to_home()
   5104     card = c.dev.dump()
   5105     c.note("the balance screen: " + str(card.texts()[:14]))
   5106     for label in (r"(?i)Where to pay", r"(?i)^Shopping$"):
   5107         if c.tap(label, timeout=10):
   5108             screen = c.see(r"(?i)where to pay|website|shopping", timeout=20)
   5109             c.note("shopping: " + str(screen.texts()[:12] if screen else None))
   5110             c.check()
   5111             return
   5112     c.note("the card is there but the screen is not: with one URL the button "
   5113            "opens that site in a browser, and reaching ExchangeShoppingScreen "
   5114            "needs one scope carrying two")
   5115     c.check()
   5116 
   5117 
   5118 @scenario("cancel_in_flight", setup="funded",
   5119           about="back out of prompts while they are still loading")
   5120 def s_cancel_in_flight(c: Ctx) -> None:
   5121     """Leaving a prompt before it has loaded, which is where a half-finished
   5122     request would show up as a stuck transaction.
   5123 
   5124     It does *not* reach `cancelProgressToken`, whatever this docstring used to
   5125     claim: that operation has exactly one caller,
   5126     `WalletBackendApi.cancelDatabaseMigration`, and the only thing that offers
   5127     a database migration is a wallet whose database is still in the IndexedDB
   5128     emulation.  `MainViewModel` hard-codes `useNativeDb = true`, so a new
   5129     install never has one, and `taler-wallet-cli`'s database is native too --
   5130     so nothing in this environment can produce the legacy format, and
   5131     `cancelProgressToken`, `migrateDatabase` and the migration UI stay out of
   5132     reach without a database written by an older wallet.
   5133     """
   5134     order = c.merchant.create_order("EUR:1", summary="Cancelled while loading")
   5135     for delay in (0.3, 1.0, 2.0):
   5136         c.dev.send_uri(order["pay_uri"])
   5137         time.sleep(delay)
   5138         c.dev.back()
   5139         time.sleep(1.5)
   5140         c.note(f"after backing out {delay}s in: {c.dev.dump().texts()[:8]}")
   5141         c.check()
   5142         c.back_to_home()
   5143     # The same for a withdrawal, which takes longer to prepare.
   5144     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
   5145     for delay in (0.3, 1.5):
   5146         c.dev.send_uri(op["taler_withdraw_uri"])
   5147         time.sleep(delay)
   5148         c.dev.back()
   5149         time.sleep(1.5)
   5150         c.note(f"withdrawal, backed out {delay}s in: {c.dev.dump().texts()[:8]}")
   5151         c.check()
   5152         c.back_to_home()
   5153     # Nothing should be left half-done.
   5154     c.ep.check_database()
   5155     rows = transaction_rows(open_transactions(c))
   5156     c.note(f"{len(rows)} transactions after cancelling: "
   5157            f"{[n.label[:22] for n in rows]}")
   5158     c.check()
   5159 
   5160 
   5161 @scenario("alias_registration", setup="funded",
   5162           about="the Taldir alias registration form")
   5163 def s_alias_registration(c: Ctx) -> None:
   5164     """Fill and submit the alias form.
   5165 
   5166     No Taldir service runs in this stack, so registration is expected to fail;
   5167     the point is the screen itself, which nothing else reaches, and that the
   5168     failure is reported rather than swallowed.
   5169     """
   5170     c.app.open_settings()
   5171     c.app.scroll_to_text(r"(?i)^Alias Registration$", max_scrolls=12)
   5172     c.must_tap(r"(?i)^Alias Registration$")
   5173     screen = c.require(r"(?i)Alias|Duration|Register", timeout=25)
   5174     c.note("alias screen: " + str(screen.texts()[:14]))
   5175     c.check()
   5176     # The type picker is a dropdown: choosing from it leaves the menu open, and
   5177     # a "Register Alias" tap underneath it does nothing at all, which is how
   5178     # this scenario used to report a submission it never made.
   5179     for kind, value in ((r"(?i)^email$", "simulator@example.com"),
   5180                         (r"(?i)^phone$", "+10000000000")):
   5181         if c.tap(r"(?i)Alias Type", timeout=8):
   5182             c.tap(kind, timeout=8)
   5183             time.sleep(1)
   5184             c.check()
   5185         if not c.fill(value):
   5186             c.note(f"no alias field for {value!r}")
   5187             break
   5188         time.sleep(1)
   5189         if not c.tap(r"(?i)^Register Alias$", timeout=12):
   5190             c.note("the register button is not tappable")
   5191             break
   5192         # Registration goes to the hard-coded https://taldir.gnunet.org, which
   5193         # is not reachable from here, so what matters is whether the screen
   5194         # says so.
   5195         time.sleep(8)
   5196         after = c.dev.dump()
   5197         c.note(f"{value!r} -> {after.texts()[:14]}")
   5198         if after.find(r"(?i)error|failed|could not|unreachable|retry") is None:
   5199             c.note("WARNING: no sign on screen that the registration failed")
   5200         c.check()
   5201     c.ep.check_database()
   5202 
   5203 
   5204 @scenario("uri_storm", setup="funded",
   5205           about="many URIs in rapid succession, valid and malformed")
   5206 def s_uri_storm(c: Ctx) -> None:
   5207     """Fire URIs faster than the app can finish handling them.
   5208 
   5209     Each one starts an asynchronous request; overlapping them is where a
   5210     half-initialised screen or a lost cancellation would show up.
   5211     """
   5212     order = c.merchant.create_order("EUR:1", summary="Storm order")
   5213     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
   5214     storm = [
   5215         order["pay_uri"],
   5216         op["taler_withdraw_uri"],
   5217         corpus.MALFORMED["bad_base32"],
   5218         corpus.STRUCTURAL["pay"],
   5219         corpus.MALFORMED["huge"],
   5220         order["pay_uri"],
   5221         corpus.STRUCTURAL["withdraw_exchange"],
   5222         corpus.MALFORMED["unknown_action"],
   5223     ]
   5224     for round_number in range(3):
   5225         for uri in storm:
   5226             c.dev.send_uri(uri)
   5227             time.sleep(0.35)
   5228         time.sleep(3)
   5229         screen = c.dev.dump()
   5230         c.note(f"after burst {round_number + 1}: {screen.texts()[:10]}")
   5231         c.check()
   5232         c.back_to_home()
   5233     # Everything should still work afterwards.
   5234     c.app.home()
   5235     rows = transaction_rows(open_transactions(c))
   5236     c.note(f"{len(rows)} transactions after the storm")
   5237     c.check()
   5238     c.ep.check_database()
   5239 
   5240 
   5241 @scenario("long_text_fields", setup="funded",
   5242           about="very long input in every text field that will take it")
   5243 def s_long_text(c: Ctx) -> None:
   5244     blob = "A" * 4000
   5245     places = [
   5246         (r"(?i)^Send$", r"(?i)Send money|Amount to send|Purpose"),
   5247         (r"(?i)^Request$", r"(?i)Request money|Amount to receive"),
   5248     ]
   5249     for entry, marker in places:
   5250         c.back_to_home()
   5251         if not c.tap(entry, timeout=20):
   5252             continue
   5253         screen = c.see(marker, timeout=25)
   5254         if screen is None:
   5255             continue
   5256         # The purpose/summary field takes free text; the amount field does not.
   5257         fields = screen.editable()
   5258         c.note(f"{entry}: {len(fields)} editable fields")
   5259         for index in range(len(fields)):
   5260             if not c.fill(blob, index):
   5261                 continue
   5262             time.sleep(1.5)
   5263             after = c.dev.dump()
   5264             c.note(f"  field {index} after 4000 chars: {after.texts()[:6]}")
   5265             c.check()
   5266         c.back_to_home()
   5267     c.ep.check_database()
   5268 
   5269 
   5270 @scenario("withdraw_age_restricted", setup="fresh",
   5271           about="withdraw coins restricted to an age group")
   5272 def s_withdraw_age(c: Ctx) -> None:
   5273     """The age picker only appears when the exchange offers age-restricted
   5274     denominations, which the simulator's exchange now does."""
   5275     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:10")
   5276     c.app.handle_uri(op["taler_withdraw_uri"])
   5277     screen = c.require(r"(?i)Confirm withdrawal|Total amount", timeout=60)
   5278     c.note("withdrawal prompt: " + str(screen.texts()[:14]))
   5279     if not c.tap(r"(?i)Restrict usage to age|^Unrestricted$", timeout=15):
   5280         c.note("no age restriction offered")
   5281         return
   5282     picker = c.dev.dump()
   5283     c.note("age options: " + str(picker.texts()[:14]))
   5284     c.check()
   5285     chosen = None
   5286     for age in (r"(?i)^12$", r"(?i)^13$", r"(?i)^16$", r"(?i)^18$"):
   5287         if c.tap(age, timeout=6):
   5288             chosen = age
   5289             break
   5290     c.note(f"chose {chosen}")
   5291     c.check()
   5292     c.accept_tos()
   5293     c.must_tap(r"(?i)Confirm withdrawal", timeout=30)
   5294     c.see(r"(?i)Waiting for authorization|Authorize in bank", timeout=60)
   5295     deadline = time.time() + 60
   5296     while time.time() < deadline:
   5297         if c.bank.withdrawal_status(op["withdrawal_id"])["status"] == "selected":
   5298             break
   5299         time.sleep(2)
   5300     c.bank.confirm_withdrawal(*flows.WALLET_USER, op["withdrawal_id"])
   5301     for _ in range(20):
   5302         if c.dev.dump().find(r"(?i)completed successfully"):
   5303             break
   5304         time.sleep(3)
   5305     detail = c.dev.dump()
   5306     c.note("after the age-restricted withdrawal: " + str(detail.texts()[:14]))
   5307     c.tap(r"(?i)^Show JSON$", timeout=8)
   5308     c.check()
   5309     c.ep.check_database()
   5310 
   5311 
   5312 def kyc_enabled(c: Ctx) -> bool:
   5313     """Whether the stack was started from the KYC variant.
   5314 
   5315     The exchange says so itself, which is more reliable than guessing from the
   5316     config file the stack happens to have been given.
   5317     """
   5318     import urllib.request
   5319     try:
   5320         with urllib.request.urlopen(f"{c.env.exchange}keys", timeout=15) as resp:
   5321             keys = json.loads(resp.read().decode())
   5322     except Exception as e:
   5323         c.note(f"could not read the exchange's keys: {e}")
   5324         return False
   5325     if not keys.get("kyc_enabled"):
   5326         c.note("this stack has KYC switched off; start it with "
   5327                "SIM_CONF=sim-kyc.conf to exercise these paths")
   5328         return False
   5329     return True
   5330 
   5331 
   5332 @scenario("kyc_withdraw_trips_rule", setup="fresh",
   5333           about="withdraw past the KYC threshold and follow what the wallet offers",
   5334           expects=("error-screen", "unfinished-transaction", "background-error"))
   5335 def s_kyc_withdraw(c: Ctx) -> None:
   5336     """The KYC stack trips a rule above EUR:5 within a day.
   5337 
   5338     What matters here is the wallet's half: that it says identification is
   5339     needed, offers a way to start it, and does not leave the transaction
   5340     looking finished when it is not.
   5341     """
   5342     if not kyc_enabled(c):
   5343         return
   5344     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:10")
   5345     c.app.handle_uri(op["taler_withdraw_uri"])
   5346     c.accept_tos()
   5347     c.must_tap(r"(?i)confirm withdrawal", timeout=60)
   5348     c.see(r"(?i)Waiting for authorization|Authorize in bank", timeout=60)
   5349     deadline = time.time() + 60
   5350     while time.time() < deadline:
   5351         if c.bank.withdrawal_status(op["withdrawal_id"])["status"] == "selected":
   5352             break
   5353         time.sleep(2)
   5354     c.bank.confirm_withdrawal(*flows.WALLET_USER, op["withdrawal_id"])
   5355 
   5356     # Now the exchange should ask for identification rather than paying out.
   5357     kyc_screen = None
   5358     deadline = time.time() + 120
   5359     while time.time() < deadline:
   5360         screen = c.dev.dump()
   5361         if screen.find(r"(?i)KYC|identification|verify|Complete"):
   5362             kyc_screen = screen
   5363             break
   5364         if screen.find(r"(?i)completed successfully"):
   5365             c.note("the withdrawal completed without any KYC step")
   5366             break
   5367         time.sleep(4)
   5368     if kyc_screen is None:
   5369         c.note("no KYC prompt appeared: " + str(c.dev.dump().texts()[:12]))
   5370         c.check()
   5371         c.ep.check_database()
   5372         return
   5373     c.note("KYC prompt: " + str(kyc_screen.texts()[:14]))
   5374     c.check()
   5375     # Follow the call to action; it hands off to a browser, so coming back is
   5376     # part of the test.
   5377     if c.tap(r"(?i)Complete KYC|KYC required|verify|identification", timeout=20):
   5378         time.sleep(6)
   5379         after = c.dev.dump()
   5380         c.note(f"after tapping the KYC action: activity={after.activity} "
   5381                f"{after.texts()[:10]}")
   5382         c.check()
   5383         c.dev.launch()
   5384         time.sleep(4)
   5385         c.note("back in the wallet: " + str(c.dev.dump().texts()[:12]))
   5386     c.check()
   5387     c.ep.check_database()
   5388 
   5389 
   5390 @scenario("kyc_transaction_actions", setup="fresh",
   5391           about="what a KYC-blocked transaction offers in its detail screen",
   5392           expects=("error-screen", "unfinished-transaction", "background-error"))
   5393 def s_kyc_actions(c: Ctx) -> None:
   5394     if not kyc_enabled(c):
   5395         return
   5396     op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:10")
   5397     c.app.handle_uri(op["taler_withdraw_uri"])
   5398     c.accept_tos()
   5399     c.must_tap(r"(?i)confirm withdrawal", timeout=60)
   5400     deadline = time.time() + 60
   5401     while time.time() < deadline:
   5402         if c.bank.withdrawal_status(op["withdrawal_id"])["status"] == "selected":
   5403             break
   5404         time.sleep(2)
   5405     c.bank.confirm_withdrawal(*flows.WALLET_USER, op["withdrawal_id"])
   5406     time.sleep(25)
   5407     screen = open_transactions(c)
   5408     rows = transaction_rows(screen)
   5409     c.note(f"{len(rows)} transactions: {[n.label[:24] for n in rows]}")
   5410     if rows:
   5411         c.dev.tap_node(rows[0], screen)
   5412         time.sleep(3)
   5413         detail = c.dev.dump()
   5414         c.note("KYC-blocked transaction: " + str(detail.texts()[:16]))
   5415         c.check()
   5416         for action in (r"(?i)^Show JSON$", r"(?i)^Retry$", r"(?i)^Suspend$",
   5417                        r"(?i)^Resume$"):
   5418             if c.tap(action, timeout=8):
   5419                 c.check()
   5420                 c.dev.back()
   5421                 time.sleep(1)
   5422     c.ep.check_database()
   5423 
   5424 
   5425 def twister_or_skip(c: Ctx) -> Twister | None:
   5426     """The fault injector, or None when the stack was not started with it.
   5427 
   5428     Only the sim-twister.conf variant puts a proxy in front of the exchange;
   5429     on an ordinary stack these scenarios have nothing to break and say so
   5430     rather than failing.
   5431     """
   5432     env_file = Path("/opt/taler-sim/run/stack/env.json")
   5433     try:
   5434         if not json.loads(env_file.read_text()).get("twister"):
   5435             c.note("the stack is not running twister; nothing to inject")
   5436             return None
   5437     except (OSError, json.JSONDecodeError):
   5438         c.note("no stack env.json; cannot tell whether twister is running")
   5439         return None
   5440     try:
   5441         twister = Twister()
   5442         if not twister.alive():
   5443             c.note("twister is configured but not answering")
   5444             return None
   5445         return twister
   5446     except TwisterUnavailable as e:
   5447         c.note(f"twister unavailable: {e}")
   5448         return None
   5449 
   5450 
   5451 @scenario("twister_withdraw_faults", setup="fresh",
   5452           about="damage the exchange's replies during a withdrawal",
   5453           expects=("error-screen", "background-error", "stuck-operation",
   5454                    "unfinished-transaction"))
   5455 def s_twister_withdraw(c: Ctx) -> None:
   5456     """Each fault is armed, then a withdrawal is attempted.
   5457 
   5458     What is being checked is the shape of the failure: a refusal the user can
   5459     read, or a retry, rather than an internal error, a blank screen or a
   5460     transaction that sits there for ever.
   5461     """
   5462     twister = twister_or_skip(c)
   5463     if twister is None:
   5464         return
   5465     for name, arm in FAULTS.items():
   5466         c.app.fresh_start(dev_mode=True)
   5467         c.dev.logcat(clear=True)
   5468         op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
   5469         # The fault stays armed for the whole withdrawal: one arming would be
   5470         # spent on whichever poll happened to come first.
   5471         with twister.armed(arm) as a:
   5472             c.app.handle_uri(op["taler_withdraw_uri"])
   5473             time.sleep(6)
   5474             screen = c.dev.dump()
   5475             c.note(f"{name}: {screen.texts()[:10]}")
   5476             c.check()
   5477             # Try to carry on: the wallet should either recover or explain itself.
   5478             c.accept_tos()
   5479             c.tap(r"(?i)confirm withdrawal|^Retry$", timeout=15)
   5480             time.sleep(6)
   5481             c.note(f"{name} after retry: {c.dev.dump().texts()[:10]}")
   5482             c.check()
   5483         if a.errors:
   5484             c.note(f"{name}: arming complained: {a.errors}")
   5485         c.note(f"{name}: armed {a.fired} times")
   5486         # ... and recover with the fault gone, so a permanent failure is
   5487         # distinguishable from one the wallet retries out of.
   5488         time.sleep(8)
   5489         c.note(f"{name} once the fault stops: {c.dev.dump().texts()[:10]}")
   5490         c.check()
   5491     c.ep.check_database()
   5492 
   5493 
   5494 @scenario("twister_payment_faults", setup="funded",
   5495           about="damage the exchange's replies during a payment",
   5496           expects=("error-screen", "background-error", "stuck-operation",
   5497                    "unfinished-transaction"))
   5498 def s_twister_payment(c: Ctx) -> None:
   5499     twister = twister_or_skip(c)
   5500     if twister is None:
   5501         return
   5502     # Seven payments of EUR:1, each of which may strand coins on a purchase
   5503     # that cannot finish, exhaust the EUR:10 the fixture withdraws: the last
   5504     # faults then measure "Insufficient balance" rather than the fault.
   5505     flows.withdraw(c.app, c.bank, "EUR:20")
   5506     c.back_to_home()
   5507     recovered = {}
   5508     for name, arm in FAULTS.items():
   5509         order = c.merchant.create_order("EUR:1", summary=f"Order during {name}")
   5510         # Only the exchange sits behind the proxy, so the prompt itself comes
   5511         # through intact and the fault has to survive until the coins are
   5512         # deposited -- which only happens once "Pay" is tapped.
   5513         with twister.armed(arm) as a:
   5514             c.app.handle_uri(order["pay_uri"])
   5515             screen = c.require(r"(?i)^Pay\b|Review order|Total", timeout=40)
   5516             c.note(f"{name} prompt: {screen.texts()[:10]}")
   5517             c.must_tap(r"(?i)^Pay\b", timeout=30)
   5518             time.sleep(8)
   5519             c.note(f"{name} after paying: {c.dev.dump().texts()[:12]}")
   5520             c.check()
   5521             status = c.merchant.order_status(order["order_id"], order["token"])
   5522             c.note(f"{name}: merchant says {status.get('order_status')}")
   5523         c.note(f"{name}: armed {a.fired} times")
   5524         # With the fault gone the payment should either complete or fail for
   5525         # good.  Retries have a backoff, so this has to wait properly: the
   5526         # finding would be a purchase that never resolves either way.
   5527         # Five minutes, not ninety seconds: the first fault-injection phase
   5528         # reported every payment still "claimed" after 90s, which says nothing
   5529         # -- wallet-core retries with a backoff, and a deposit that has not
   5530         # been retried yet looks exactly like one that never will.  Long
   5531         # enough to tell those apart, and the elapsed time is recorded so a
   5532         # slow recovery can be told from none.
   5533         started = time.time()
   5534         deadline = started + 300
   5535         final = None
   5536         while time.time() < deadline:
   5537             final = c.merchant.order_status(order["order_id"],
   5538                                             order["token"]).get("order_status")
   5539             if final == "paid":
   5540                 break
   5541             time.sleep(10)
   5542         recovered[name] = final
   5543         c.note(f"{name}: {int(time.time() - started)}s after the fault "
   5544                f"stopped the merchant says {final}; screen "
   5545                f"{c.dev.dump().texts()[:10]}")
   5546         c.check()
   5547         c.back_to_home()
   5548     c.note("recovery per fault: " + str(recovered))
   5549     stuck = [k for k, v in recovered.items() if v != "paid"]
   5550     if stuck:
   5551         c.note(f"WARNING: these payments never completed: {stuck}")
   5552     c.ep.check_database()
   5553 
   5554 
   5555 @scenario("twister_field_faults", setup="fresh",
   5556           about="delete and rewrite fields of the exchange's replies",
   5557           expects=("error-screen", "background-error", "stuck-operation",
   5558                    "unfinished-transaction"))
   5559 def s_twister_fields(c: Ctx) -> None:
   5560     """Structural damage rather than transport damage: a reply that parses but
   5561     is missing a field, or carries a wrong one."""
   5562     twister = twister_or_skip(c)
   5563     if twister is None:
   5564         return
   5565     # Twister walks dot paths and takes a numeric token as an array index, so
   5566     # a nested field can be named exactly: "denoms" alone is not a key of
   5567     # /keys and silently matched nothing.
   5568     cases = [
   5569         ("delete-denominations", lambda t: t.delete("denominations")),
   5570         ("delete-denom-list", lambda t: t.delete("denominations.0.denoms")),
   5571         ("delete-signature", lambda t: t.delete("exchange_sig")),
   5572         ("flip-master-pub", lambda t: t.flip("master_public_key")),
   5573         ("flip-denom-sig", lambda t: t.flip("denominations.0.denoms.0.master_sig")),
   5574         ("delete-wire-fees", lambda t: t.delete("wire_fees")),
   5575         ("rewrite-version", lambda t: t.modify("version", "999:0:0")),
   5576         ("rewrite-currency", lambda t: t.modify("currency", "XXX")),
   5577         ("rewrite-base-url", lambda t: t.modify("base_url", "http://elsewhere.invalid/")),
   5578     ]
   5579     for name, arm in cases:
   5580         c.app.fresh_start(dev_mode=True)
   5581         c.dev.logcat(clear=True)
   5582         op = c.bank.create_withdrawal(*flows.WALLET_USER, "EUR:5")
   5583         with twister.armed(arm) as a:
   5584             c.app.handle_uri(op["taler_withdraw_uri"])
   5585             time.sleep(7)
   5586             c.note(f"{name}: {c.dev.dump().texts()[:12]}")
   5587             c.check()
   5588             c.accept_tos()
   5589             c.accept_tos()
   5590             c.tap(r"(?i)confirm withdrawal", timeout=10)
   5591             time.sleep(6)
   5592             c.note(f"{name} after confirming: {c.dev.dump().texts()[:12]}")
   5593             c.check()
   5594         if a.errors:
   5595             c.note(f"{name}: arming complained: {a.errors}")
   5596         c.note(f"{name}: armed {a.fired} times")
   5597     c.ep.check_database()
   5598 
   5599 
   5600 @scenario("memory_pressure", setup="paid",
   5601           about="trim memory and background the app mid-flow")
   5602 def s_memory_pressure(c: Ctx) -> None:
   5603     """What Android does to an app it wants memory back from.
   5604 
   5605     TRIM_MEMORY_RUNNING_CRITICAL while a prompt is open, then a trip through
   5606     the background, is where a screen that kept state outside the saved
   5607     instance falls over.
   5608     """
   5609     from device import PKG
   5610     order = c.merchant.create_order("EUR:1", summary="Order under memory pressure")
   5611     c.app.handle_uri(order["pay_uri"])
   5612     c.require(r"(?i)Review order|Total:|^Pay", timeout=60)
   5613     pid = c.dev.shell(f"pidof {PKG}", check=False).strip().split()[0:1]
   5614     c.note(f"pid: {pid}")
   5615     for level in ("RUNNING_MODERATE", "RUNNING_LOW", "RUNNING_CRITICAL"):
   5616         c.dev.shell(f"am send-trim-memory {PKG} {level}", check=False)
   5617         time.sleep(1.5)
   5618     c.note("after trimming: " + str(c.dev.dump().texts()[:10]))
   5619     c.check()
   5620     # Background the app, trim again, come back.
   5621     c.dev.key("KEYCODE_HOME")
   5622     time.sleep(2)
   5623     c.dev.shell(f"am send-trim-memory {PKG} COMPLETE", check=False)
   5624     time.sleep(2)
   5625     c.dev.launch()
   5626     time.sleep(4)
   5627     restored = c.dev.dump()
   5628     c.note("after returning: " + str(restored.texts()[:12]))
   5629     c.check()
   5630     # The prompt should either still be there or be gone cleanly; either way
   5631     # the wallet has to work afterwards.
   5632     c.back_to_home()
   5633     rows = transaction_rows(open_transactions(c))
   5634     c.note(f"{len(rows)} transactions afterwards")
   5635     c.check()
   5636     c.ep.check_database()
   5637 
   5638 
   5639 @scenario("rapid_taps", setup="funded",
   5640           about="hammer confirm buttons faster than the app can respond")
   5641 def s_rapid_taps(c: Ctx) -> None:
   5642     """Double-submission is the classic way to pay twice or abort twice."""
   5643     order = c.merchant.create_order("EUR:1", summary="Hammered order")
   5644     c.app.handle_uri(order["pay_uri"])
   5645     screen = c.require(r"(?i)Review order|^Pay", timeout=60)
   5646     pay = screen.find(r"(?i)^Pay\b")
   5647     if pay is None:
   5648         c.note("no pay button: " + str(screen.texts()[:10]))
   5649         return
   5650     target = screen.tap_target(pay)
   5651     x, y = target.center
   5652     for _ in range(6):
   5653         c.dev.tap(x, y)
   5654         time.sleep(0.15)
   5655     time.sleep(6)
   5656     c.note("after hammering pay: " + str(c.dev.dump().texts()[:12]))
   5657     c.check()
   5658     status = c.merchant.order_status(order["order_id"], order["token"])
   5659     c.note(f"order status: {status.get('order_status')}, refunded: {status.get('refunded')}")
   5660     # One payment, not six.
   5661     rows = transaction_rows(open_transactions(c))
   5662     purchases = [n.label for n in rows]
   5663     c.note(f"transactions: {purchases}")
   5664     c.check()
   5665     c.ep.check_database()
   5666 
   5667 
   5668 # -------------------------------------------------------------------- runner ---
   5669 
   5670 SETUPS: dict[str, Callable] = {
   5671     "fresh": lambda app, env: app.fresh_start(dev_mode=True),
   5672     "funded": flows.fund_wallet,
   5673     "paid": flows.funded_and_paid,
   5674     "keep": lambda app, env: app.home(),
   5675 }
   5676 
   5677 
   5678 def run(names: list[str], serial: str = SERIAL) -> dict:
   5679     env = Env.load()
   5680     dev = Device(serial)
   5681     stamp = int(time.time())
   5682     results = []
   5683     all_findings: dict[str, oracles.Finding] = {}
   5684 
   5685     for name in names:
   5686         sc = REGISTRY[name]
   5687         ep = Episode(dev, OUT, name=f"suite-w{WORKER}-{stamp}-{name}",
   5688                      coverage_dir=COVERAGE)
   5689         c = Ctx(ep, env)
   5690         status, error = "ok", None
   5691         started = time.time()
   5692         try:
   5693             SETUPS[sc.setup](ep.app, env)
   5694             # Only what the scenario itself provokes should count.
   5695             ep.session = oracles.Session()
   5696             dev.logcat(clear=True)
   5697             sc.fn(c)
   5698             ep.observe()
   5699         except Exception as e:
   5700             status = "driver-error"
   5701             error = f"{type(e).__name__}: {e}"
   5702             traceback.print_exc(limit=3)
   5703         expected = [f for f in ep.session.findings.values() if f.kind in sc.expects]
   5704         summary = ep.finish({"scenario": name, "setup": sc.setup, "status": status,
   5705                              "error": error, "notes": c.notes,
   5706                              "expected_findings": [f.fingerprint for f in expected],
   5707                              "seconds": round(time.time() - started, 1)})
   5708         summary["serious"] = len([f for f in ep.session.serious()
   5709                                   if f.kind not in sc.expects])
   5710         all_findings.update({k: v for k, v in ep.session.findings.items()
   5711                              if v.kind not in sc.expects})
   5712         results.append(summary)
   5713         print(f"  {name:26} {status:13} {summary['serious']} serious, "
   5714               f"{len(summary['findings'])} total, {summary['seconds']}s")
   5715         for f in ep.session.findings.values():
   5716             print(f"      [{f.kind}] {f.detail[:150]}")
   5717 
   5718     out = {
   5719         "stamp": stamp,
   5720         "scenarios": results,
   5721         "findings": [f.__dict__ | {"fingerprint": f.fingerprint}
   5722                      for f in all_findings.values()],
   5723     }
   5724     (OUT / f"suite-w{WORKER}-{stamp}-summary.json").write_text(json.dumps(out, indent=2))
   5725     # oracles.INFORMATIONAL, not just "error-screen": this tally used its own
   5726     # narrower rule, so a withdrawal left pending on purpose -- every manual
   5727     # withdrawal the suite starts and never wires money to sits in
   5728     # PendingQueryingStatus forever, by design -- was counted as a serious
   5729     # finding twice a round and triaged again every time.
   5730     serious = [f for f in all_findings.values()
   5731                if f.kind not in oracles.INFORMATIONAL]
   5732     print(f"\n{len(results)} scenarios, "
   5733           f"{sum(1 for r in results if r['status'] == 'ok')} ok, "
   5734           f"{len(all_findings)} findings ({len(serious)} serious)")
   5735     print(f"summary: {OUT}/suite-w{WORKER}-{stamp}-summary.json")
   5736     return out
   5737 
   5738 
   5739 def main() -> int:
   5740     args = [a for a in sys.argv[1:] if not a.startswith("-")]
   5741     if "--list" in sys.argv:
   5742         for name, sc in REGISTRY.items():
   5743             print(f"{name:26} [{sc.setup}] {sc.about.strip().splitlines()[0][:70]}")
   5744         return 0
   5745     names = args or list(REGISTRY)
   5746     unknown = [n for n in names if n not in REGISTRY]
   5747     if unknown:
   5748         print(f"unknown scenarios: {unknown}\nknown: {list(REGISTRY)}")
   5749         return 2
   5750     out = run(names)
   5751     return 0 if all(r["status"] == "ok" for r in out["scenarios"]) else 1
   5752 
   5753 
   5754 if __name__ == "__main__":
   5755     sys.exit(main())