taler-android

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

qrsuite.py (8947B)


      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 """Decode real QR images with the app, through its own scan screen.
     15 
     16 Everything else in the simulator hands URIs to the app as shared text, which
     17 skips the decoder entirely.  Here the payload is rendered to a PNG with
     18 `qrencode`, pushed into the device's gallery and picked with the scan screen's
     19 "Scan from gallery", so the image decoder and everything downstream of it run
     20 for real.
     21 
     22 The live camera was tried first and does not work unattended: the emulator's
     23 virtual scene hangs its poster on a wall that is rotated away from the default
     24 camera pose (`Toren1BD.posters`: `rotation 0 -150 0`), and the pose cannot be
     25 moved from outside. `--camera` keeps that path available for a human to watch.
     26 
     27     python3 qrsuite.py --worker 4
     28     python3 qrsuite.py --worker 4 --only valid_withdraw malformed_base32
     29 """
     30 
     31 from __future__ import annotations
     32 
     33 import argparse
     34 import json
     35 import subprocess
     36 import sys
     37 import time
     38 from pathlib import Path
     39 
     40 sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "corpus"))
     41 
     42 import oracles  # noqa: E402
     43 import uris as corpus  # noqa: E402
     44 from device import Device  # noqa: E402
     45 from episode import Episode  # noqa: E402
     46 from stack import Bank, Env, Merchant  # noqa: E402
     47 from wallet import Wallet  # noqa: E402
     48 
     49 EMU = Path("/opt/taler-sim/emu/emu.sh")
     50 POSTERS = Path("/opt/taler-sim/run/posters")
     51 OUT = Path("/opt/taler-sim/run/out")
     52 COVERAGE = Path("/opt/taler-sim/run/coverage")
     53 
     54 
     55 def render(payload: str, name: str) -> Path:
     56     """Make a QR poster. Large modules, because the camera sees it from afar."""
     57     POSTERS.mkdir(parents=True, exist_ok=True)
     58     path = POSTERS / f"{name}.png"
     59     subprocess.run(
     60         ["qrencode", "-s", "20", "-m", "2", "-l", "L", "-o", str(path), payload],
     61         check=True, timeout=60,
     62     )
     63     return path
     64 
     65 
     66 def payloads(env: Env) -> dict[str, str]:
     67     """What to put on the wall.
     68 
     69     The valid entries point at live services but at identifiers that do not
     70     exist, so no funds are needed: reaching the prompt (or a clean error) is
     71     proof that the decode worked.
     72     """
     73     merchant = Merchant(env.merchant)
     74     bank = Bank(env.bank)
     75     out = {
     76         "valid_pay": corpus.STRUCTURAL["pay"],
     77         "valid_withdraw": corpus.STRUCTURAL["withdraw"],
     78         "valid_withdraw_exchange": corpus.STRUCTURAL["withdraw_exchange"],
     79         "payto": corpus.STRUCTURAL["payto_iban"],
     80         "malformed_base32": corpus.MALFORMED["bad_base32"],
     81         "unknown_action": corpus.MALFORMED["unknown_action"],
     82         "not_taler": "https://www.gnu.org/software/taler/",
     83         "plain_text": "this is not a URI at all",
     84     }
     85     # One genuinely live pay URI, so a successful decode leads somewhere real.
     86     try:
     87         order = merchant.create_order("EUR:1", summary="QR scanned order")
     88         out["live_pay"] = order["pay_uri"]
     89     except Exception as e:
     90         print(f"could not create a live order ({e}); skipping live_pay")
     91     try:
     92         op = bank.create_withdrawal("wallet1", "walletpass1", "EUR:5")
     93         out["live_withdraw"] = op["taler_withdraw_uri"]
     94     except Exception as e:
     95         print(f"could not create a live withdrawal ({e}); skipping live_withdraw")
     96     return out
     97 
     98 
     99 def boot_with(worker: int, poster: Path) -> None:
    100     subprocess.run([str(EMU), "kill", str(worker)], timeout=120, check=False)
    101     time.sleep(3)
    102     env = {"SIM_POSTER": str(poster), "PATH": "/usr/bin:/bin:/usr/sbin:/sbin"}
    103     subprocess.run([str(EMU), "boot", str(worker)], timeout=600, check=True,
    104                    env={**env})
    105     subprocess.run([str(EMU), "prepare", str(worker)], timeout=600, check=True)
    106 
    107 
    108 def push_to_gallery(dev: Device, poster: Path) -> None:
    109     """Put the image where the system photo picker will offer it."""
    110     target = f"/sdcard/Pictures/{poster.name}"
    111     dev.adb("push", str(poster), target, timeout=120)
    112     # MediaStore has to learn about the file, or the picker shows nothing.
    113     dev.shell(f"am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE "
    114               f"-d file://{target}", check=False)
    115     time.sleep(1.5)
    116 
    117 
    118 def scan_from_gallery(dev: Device, app: Wallet, ep: Episode, name: str,
    119                       payload: str, poster: Path, settle: int = 20) -> dict:
    120     """Pick the rendered QR image with the scan screen's gallery button."""
    121     app.fresh_start(dev_mode=True)
    122     push_to_gallery(dev, poster)
    123     dev.logcat(clear=True)
    124     screen = app.open_scanner()
    125     before = screen.signature()
    126     dev.tap_text(r"(?i)Scan from gallery", timeout=30)
    127     time.sleep(3)
    128     picker = dev.dump()
    129     photo = picker.find(r"(?i)^Photo taken on") or picker.find(r"(?i)photo")
    130     if photo is None:
    131         return {"payload": payload[:120], "error": "no photo in the picker",
    132                 "screen": picker.texts()[:12]}
    133     dev.tap_node(photo, picker)
    134     start = time.time()
    135     reacted = None
    136     while time.time() - start < settle:
    137         current = dev.dump()
    138         if current.signature() != before and "photopicker" not in current.activity:
    139             reacted = current
    140             break
    141         time.sleep(2)
    142     after = reacted or dev.dump()
    143     ep.observe()
    144     result = {
    145         "payload": payload[:120],
    146         "decoded_and_reacted": reacted is not None,
    147         "screen": after.texts()[:14],
    148         "seconds": round(time.time() - start, 1),
    149     }
    150     print(f"  {name:24} reacted={result['decoded_and_reacted']} "
    151           f"{result['screen'][:6]}")
    152     return result
    153 
    154 
    155 def scan_with_camera(dev: Device, app: Wallet, ep: Episode, name: str,
    156                      payload: str, settle: int = 25) -> dict:
    157     """Open the scan screen and see what the camera makes of the wall."""
    158     app.fresh_start(dev_mode=True)
    159     dev.logcat(clear=True)
    160     screen = app.open_scanner()
    161     start = time.time()
    162     reacted = None
    163     while time.time() - start < settle:
    164         current = dev.dump()
    165         if current.signature() != screen.signature():
    166             reacted = current
    167             break
    168         time.sleep(2)
    169     after = reacted or dev.dump()
    170     ep.observe()
    171     result = {
    172         "payload": payload[:120],
    173         "decoded_and_reacted": reacted is not None,
    174         "screen": after.texts()[:14],
    175         "seconds": round(time.time() - start, 1),
    176     }
    177     print(f"  {name:24} reacted={result['decoded_and_reacted']} "
    178           f"{result['screen'][:6]}")
    179     return result
    180 
    181 
    182 def main() -> int:
    183     ap = argparse.ArgumentParser(description=__doc__)
    184     ap.add_argument("--worker", type=int, default=4)
    185     ap.add_argument("--only", nargs="*")
    186     ap.add_argument("--camera", action="store_true",
    187                     help="use the virtual scene's camera instead of the gallery "
    188                          "(needs a human to aim it; see the module docstring)")
    189     args = ap.parse_args()
    190 
    191     env = Env.load()
    192     cases = payloads(env)
    193     if args.only:
    194         cases = {k: v for k, v in cases.items() if k in args.only}
    195     serial = f"emulator-{5554 + 2 * args.worker}"
    196     stamp = int(time.time())
    197     results: dict[str, dict] = {}
    198 
    199     dev = Device(serial)
    200     app = Wallet(dev)
    201     for name, payload in cases.items():
    202         poster = render(payload, name)
    203         print(f"{name}: {poster} ({poster.stat().st_size} bytes)")
    204         if args.camera:
    205             boot_with(args.worker, poster)
    206             dev = Device(serial)
    207             app = Wallet(dev)
    208         ep = Episode(dev, OUT, name=f"qr-w{args.worker}-{stamp}-{name}",
    209                      coverage_dir=COVERAGE)
    210         try:
    211             if args.camera:
    212                 results[name] = scan_with_camera(dev, app, ep, name, payload)
    213             else:
    214                 results[name] = scan_from_gallery(dev, app, ep, name, payload, poster)
    215         except Exception as e:
    216             results[name] = {"error": f"{type(e).__name__}: {e}"}
    217             print(f"  {name:24} ERROR {e}")
    218         ep.finish({"qr_case": name, "result": results[name]})
    219 
    220     summary = OUT / f"qr-w{args.worker}-{stamp}-summary.json"
    221     summary.write_text(json.dumps(results, indent=2))
    222     decoded = [k for k, v in results.items() if v.get("decoded_and_reacted")]
    223     print(f"\n{len(results)} QR codes scanned, {len(decoded)} produced a reaction: "
    224           f"{decoded}")
    225     print(f"summary: {summary}")
    226     return 0
    227 
    228 
    229 if __name__ == "__main__":
    230     raise SystemExit(main())