taler-android

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

cli.py (11801B)


      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 """taler-wallet-cli as the wallet's peer.
     15 
     16 Peer-to-peer payments need a second wallet.  A command-line wallet on the host
     17 is far cheaper than a second emulator and just as real from the app's point of
     18 view: it holds its own coins at the same exchange and exchanges the same URIs.
     19 """
     20 
     21 from __future__ import annotations
     22 
     23 import json
     24 import os
     25 import re
     26 import subprocess
     27 import time
     28 from pathlib import Path
     29 
     30 BINARY = "taler-wallet-cli"
     31 URI_RE = re.compile(r"taler(?:\+http)?://[^\s'\"]+")
     32 
     33 
     34 class CliWallet:
     35     def __init__(self, db: str | Path | None = None, timeout: int = 300):
     36         # One database per worker: the peer wallet is state, like the app's.
     37         if db is None:
     38             worker = os.environ.get("SIM_WORKER", "0")
     39             # The extension picks the backend, and this build no longer has the
     40             # JSON/in-memory one ("memory backend not supported").
     41             db = f"/opt/taler-sim/run/cli-wallet-{worker}.sqlite3"
     42         self.db = str(db)
     43         self.timeout = timeout
     44 
     45     def run(self, *args: str, check: bool = True) -> str:
     46         proc = subprocess.run(
     47             [BINARY, "--wallet-db", self.db, "--non-interactive", *args],
     48             capture_output=True, text=True, timeout=self.timeout,
     49         )
     50         if check and proc.returncode != 0:
     51             raise RuntimeError(
     52                 f"{BINARY} {' '.join(args)} failed ({proc.returncode}): "
     53                 f"{(proc.stderr or proc.stdout)[-600:]}"
     54             )
     55         return proc.stdout + proc.stderr
     56 
     57     def reset(self) -> None:
     58         for suffix in ("", "-wal", "-shm"):
     59             Path(self.db + suffix).unlink(missing_ok=True)
     60 
     61     def add_exchange(self, exchange: str) -> str:
     62         """Teach the peer wallet about an exchange and accept its terms."""
     63         out = self.run("exchanges", "add", exchange, check=False)
     64         return out + self.run("exchanges", "accept-tos", exchange, check=False)
     65 
     66     def fund_via_bank(self, bank, user: tuple[str, str], amount: str,
     67                       exchange: str, timeout: int = 150) -> str:
     68         """Fund the peer wallet with a bank-integrated withdrawal.
     69 
     70         `withdraw --exchange --amount` would create a *manual* withdrawal that
     71         waits for a wire transfer nobody is going to make, and `withdraw --uri`
     72         does not always get as far as choosing an exchange, which leaves the
     73         bank refusing to confirm ("Cannot confirm an unselected withdrawal").
     74         So the exchange is selected through the same wallet-core call the app
     75         uses, and only then is the operation confirmed in the bank.
     76         """
     77         self.add_exchange(exchange)
     78         op = bank.create_withdrawal(*user, amount)
     79         accepted = self.api("acceptBankIntegratedWithdrawal", {
     80             "talerWithdrawUri": op["taler_withdraw_uri"],
     81             "exchangeBaseUrl": exchange,
     82         })
     83         if "master public key" in json.dumps(accepted):
     84             # The stack was rebuilt since this wallet last ran, so its memory
     85             # of the exchange is stale; start it over rather than carrying a
     86             # wallet that refuses to talk to the only exchange there is.
     87             self.reset()
     88             self.add_exchange(exchange)
     89             op = bank.create_withdrawal(*user, amount)
     90             accepted = self.api("acceptBankIntegratedWithdrawal", {
     91                 "talerWithdrawUri": op["taler_withdraw_uri"],
     92                 "exchangeBaseUrl": exchange,
     93             })
     94         result = accepted.get("result") or {}
     95         transaction = result.get("transactionId")
     96         if not transaction:
     97             raise RuntimeError(f"the peer wallet could not accept the withdrawal: "
     98                                f"{str(accepted)[:400]}")
     99         # The CLI is not a daemon: each invocation starts wallet-core, answers
    100         # one request and exits, so the task that tells the bank which exchange
    101         # was chosen only runs while something is waiting on the transaction.
    102         # "--state pending" is useless for that -- the transaction is already
    103         # pending, so the wait returns before any task has run.  "pending/idle"
    104         # is the state that means the wallet has done all it can and is now
    105         # waiting on the bank.
    106         self.pump(transaction, "pending/idle", 90)
    107         deadline = time.time() + 90
    108         while time.time() < deadline:
    109             if bank.withdrawal_status(op["withdrawal_id"])["status"] == "selected":
    110                 break
    111             self.pump(transaction, "pending/idle", 30)
    112             time.sleep(2)
    113         else:
    114             raise RuntimeError(f"the bank never saw an exchange selected for {amount}")
    115         bank.confirm_withdrawal(*user, op["withdrawal_id"])
    116         # Pump the task loop again so the coins are actually withdrawn.
    117         self.pump(transaction, "final", 120)
    118         return self.balance()
    119 
    120     def pump(self, transaction: str, state: str = "pending/idle",
    121              timeout: int = 60) -> str:
    122         """Run wallet-core until `transaction` reaches `state`.
    123 
    124         This is the only way to make the CLI do background work: it processes
    125         tasks while a wait is outstanding and exits as soon as it is over.
    126         """
    127         return self.run("wait-tx", "--state", state,
    128                         "--timeout", f"{timeout}s", transaction, check=False)
    129 
    130     def balance(self) -> str:
    131         return self.run("balance")
    132 
    133     def withdraw(self, exchange: str, amount: str) -> str:
    134         """Fund the peer wallet straight from the exchange, no bank UI needed."""
    135         return self.run("withdraw", "--exchange", exchange, "--amount", amount,
    136                         "--wait", "--timeout", "120s")
    137 
    138     def accept_tos(self, exchange: str) -> str:
    139         return self.run("exchanges", "accept-tos", exchange, check=False)
    140 
    141     def peer_send(self, amount: str, exchange: str,
    142                   summary: str = "from the simulator's peer") -> str:
    143         """Push money to the app; returns the taler://pay-push URI."""
    144         out = self.run_fresh_on_key_change(
    145             exchange, "peer-send", "--exchange", exchange,
    146             "--summary", summary, amount)
    147         return self._uri(out, "pay-push")
    148 
    149     def peer_request(self, amount: str,
    150                      summary: str = "invoice from the simulator's peer",
    151                      exchange: str | None = None) -> str:
    152         """Invoice the app; returns the taler://pay-pull URI."""
    153         if exchange is None:
    154             out = self.run("peer-request", "--summary", summary, amount)
    155         else:
    156             out = self.run_fresh_on_key_change(
    157                 exchange, "peer-request", "--summary", summary, amount)
    158         return self._uri(out, "pay-pull")
    159 
    160     def send_mailbox_message(self, address: str, taler_uri: str,
    161                              mailbox_base: str = "http://127.0.0.1:11000/",
    162                              petname: str = "The app under test") -> dict:
    163         """Put a real message in another wallet's mailbox.
    164 
    165         The app has no caller for `sendTalerUriMailboxMessage` -- the manager
    166         method exists and nothing invokes it -- so the sender has to be this
    167         wallet.  The envelope is encrypted for the recipient's address, which
    168         is why a hand-made POST to the service cannot stand in for it: the app
    169         reads an unreadable message and discards it without a word.
    170         """
    171         contact = {
    172             "alias": "simulator@example.com",
    173             "aliasType": "email",
    174             "mailboxBaseUri": mailbox_base,
    175             "mailboxAddress": address,
    176             "source": "local",
    177             "petname": petname,
    178             "originMailboxBaseUrl": mailbox_base,
    179             "downloadedAt": {"t_s": int(time.time())},
    180             "talerUri": "",
    181             "transactionId": "",
    182         }
    183         return self.api("sendTalerUriMailboxMessage",
    184                         {"contact": contact, "talerUri": taler_uri})
    185 
    186     def run_fresh_on_key_change(self, exchange: str, *args: str) -> str:
    187         """Run a command, starting the wallet over if its exchange moved on.
    188 
    189         Every stack start gives the exchange a new master key, and a wallet
    190         that remembers the old one refuses every operation with "the exchange
    191         changed its master public key" (7066).  Funding already coped with
    192         this; the peer commands have to as well, because a scenario may be the
    193         first thing to touch this wallet after a restart.
    194         """
    195         try:
    196             return self.run(*args)
    197         except RuntimeError as e:
    198             if "master public key" not in str(e):
    199                 raise
    200             self.reset()
    201             self.add_exchange(exchange)
    202             return self.run(*args)
    203 
    204     def _uri(self, output: str, kind: str) -> str:
    205         for match in URI_RE.finditer(output):
    206             if kind in match.group(0):
    207                 return match.group(0).rstrip(".,)")
    208         raise RuntimeError(f"no {kind} URI in output: {output[-600:]}")
    209 
    210     def api(self, operation: str, payload: dict | None = None) -> dict:
    211         """Call wallet-core directly, bypassing the CLI's prompts.
    212 
    213         `handle-uri` asks whether to accept an incoming payment, and neither
    214         `-y` nor the global `--non-interactive` answers that question off a
    215         terminal, so the peer wallet drives the two-step API itself.
    216         """
    217         out = self.run("advanced", "api", operation,
    218                        json.dumps(payload or {}), check=False)
    219         start = out.find("{")
    220         if start < 0:
    221             raise RuntimeError(f"{operation}: no JSON in {out[-400:]}")
    222         try:
    223             # The CLI prints its own lines after the response, so only the
    224             # first JSON value is ours.
    225             parsed, _ = json.JSONDecoder().raw_decode(out[start:])
    226             return parsed
    227         except json.JSONDecodeError as e:
    228             raise RuntimeError(f"{operation}: {e}; output was {out[-400:]}") from None
    229 
    230     def accept_push(self, uri: str) -> dict:
    231         """Accept an incoming push payment the app sent."""
    232         prepared = self.api("preparePeerPushCredit", {"talerUri": uri})
    233         result = prepared.get("result", {})
    234         transaction_id = result.get("transactionId")
    235         if not transaction_id:
    236             raise RuntimeError(f"preparePeerPushCredit gave no transaction: {prepared}")
    237         return self.api("confirmPeerPushCredit", {"transactionId": transaction_id})
    238 
    239     def pay_pull(self, uri: str) -> dict:
    240         """Pay an invoice the app issued."""
    241         prepared = self.api("preparePeerPullDebit", {"talerUri": uri})
    242         result = prepared.get("result", {})
    243         transaction_id = result.get("transactionId")
    244         if not transaction_id:
    245             raise RuntimeError(f"preparePeerPullDebit gave no transaction: {prepared}")
    246         return self.api("confirmPeerPullDebit", {"transactionId": transaction_id})
    247 
    248     def handle_uri(self, uri: str) -> str:
    249         """Hand a URI to the peer wallet, answering its questions.
    250 
    251         Prefer accept_push/pay_pull for peer payments; this stays for URIs that
    252         need no confirmation.
    253         """
    254         return self.run("handle-uri", "-y", uri)