taler-android

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

dbprobe.py (3834B)


      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 """Read the wallet's SQLite database by copying it off the device.
     15 
     16 wallet-core runs with `useNativeDb`, so transaction state lives in a plain
     17 SQLite file.  The app's own SELinux domain may not exec /system/bin/sqlite3,
     18 so the file (and its write-ahead log) are copied out with `run-as ... cat` and
     19 queried on the host.  The copy doubles as evidence for a finding.
     20 
     21     python3 dbprobe.py tables
     22     python3 dbprobe.py emulator-5556 schema transactions
     23     python3 dbprobe.py sql "select * from transactions limit 5"
     24 """
     25 
     26 from __future__ import annotations
     27 
     28 import sqlite3
     29 import subprocess
     30 import sys
     31 import tempfile
     32 from pathlib import Path
     33 
     34 from device import ADB, PKG, Device
     35 
     36 DB_NAME = "talerwalletdb.sqlite3"
     37 
     38 
     39 def pull(dev: Device, into: Path | None = None) -> Path:
     40     """Copy the wallet database (plus its WAL) off the device."""
     41     target_dir = into or Path(tempfile.mkdtemp(prefix="walletdb-"))
     42     target_dir.mkdir(parents=True, exist_ok=True)
     43     db = target_dir / DB_NAME
     44     for suffix in ("", "-wal", "-shm"):
     45         data = subprocess.run(
     46             [ADB, "-s", dev.serial, "exec-out", "run-as", PKG, "cat",
     47              f"files/{DB_NAME}{suffix}"],
     48             capture_output=True, timeout=180,
     49         ).stdout
     50         if data:
     51             (target_dir / f"{DB_NAME}{suffix}").write_bytes(data)
     52         elif suffix == "":
     53             raise RuntimeError("could not read the wallet database off the device")
     54     return db
     55 
     56 
     57 def connect(db: Path) -> sqlite3.Connection:
     58     conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True)
     59     conn.row_factory = sqlite3.Row
     60     return conn
     61 
     62 
     63 def tables(db: Path) -> list[str]:
     64     with connect(db) as conn:
     65         return [r[0] for r in conn.execute(
     66             "select name from sqlite_master where type='table' order by name")]
     67 
     68 
     69 def columns(db: Path, table: str) -> list[str]:
     70     with connect(db) as conn:
     71         return [r[1] for r in conn.execute(f"pragma table_info({table})")]
     72 
     73 
     74 def has_native_schema(db: Path) -> bool:
     75     """Whether this database holds the native wallet schema.
     76 
     77     A wallet that has not been migrated keeps everything in the IndexedDB
     78     emulation tables (`object_data` and friends), where none of the oracles'
     79     queries apply.  Asking first is cheaper than catching "no such table" on
     80     every query, and it distinguishes "nothing to look at" from "the probe
     81     broke".
     82     """
     83     return "operation_retries" in set(tables(db))
     84 
     85 
     86 def rows(db: Path, sql: str, limit: int = 50) -> list[sqlite3.Row]:
     87     with connect(db) as conn:
     88         return list(conn.execute(sql))[:limit]
     89 
     90 
     91 if __name__ == "__main__":
     92     args = sys.argv[1:]
     93     serial = "emulator-5554"
     94     if args and args[0].startswith("emulator-"):
     95         serial = args.pop(0)
     96     database = pull(Device(serial))
     97     print(f"# {database}")
     98     if not args or args[0] == "tables":
     99         for name in tables(database):
    100             print(name)
    101     elif args[0] == "schema":
    102         for name in args[1:] or tables(database):
    103             print(f"{name}: {', '.join(columns(database, name))}")
    104     elif args[0] == "sql":
    105         for row in rows(database, args[1]):
    106             print(dict(row))