counterparty.py (15894B)
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 """The customer: a bank account and a wallet, driven from the command line. 15 16 A point-of-sale terminal does almost nothing on its own. Every interesting 17 screen is waiting for a customer to do something -- scan the code, confirm the 18 contract, accept a refund -- or to fail to. `taler-wallet-cli` is that 19 customer, and this module is the harness's grip on it: 20 21 * **pay** a displayed order, which is what turns the payment screen into the 22 success screen; 23 * **claim without paying**, which is what puts an order in the one state the 24 terminal needs a force-delete dialog for; 25 * **walk away**, which is what the payment timeout is about; 26 * **accept a refund**, which is what clears the refund screen. 27 28 Money comes from a registered account at the demo bank. A fresh account there 29 starts at zero but has a debit threshold, so a withdrawal works immediately 30 and no funding step is needed. 31 """ 32 33 from __future__ import annotations 34 35 import base64 36 import json 37 import os 38 import shutil 39 import subprocess 40 import time 41 import urllib.error 42 import urllib.parse 43 import urllib.request 44 from dataclasses import dataclass 45 from pathlib import Path 46 from typing import Any, Optional 47 48 WALLET_CLI = os.environ.get( 49 "POS_WALLET_CLI", 50 shutil.which("taler-wallet-cli") or "/root/.local/bin/taler-wallet-cli", 51 ) 52 BANK = os.environ.get("POS_BANK", "https://bank.demo.taler.net") 53 EXCHANGE = os.environ.get("POS_EXCHANGE", "https://exchange.demo.taler.net/") 54 55 56 class WalletError(RuntimeError): 57 pass 58 59 60 def _http(method: str, url: str, *, body: Any = None, 61 auth: Optional[tuple[str, str]] = None, 62 expect: tuple[int, ...] = (200, 204)) -> Any: 63 data = json.dumps(body).encode() if body is not None else None 64 headers = {} 65 if data is not None: 66 headers["Content-Type"] = "application/json" 67 if auth: 68 raw = base64.b64encode(f"{auth[0]}:{auth[1]}".encode()).decode() 69 headers["Authorization"] = f"Basic {raw}" 70 req = urllib.request.Request(url, data=data, headers=headers, method=method) 71 try: 72 with urllib.request.urlopen(req, timeout=40) as resp: 73 payload, status = resp.read(), resp.status 74 except urllib.error.HTTPError as e: 75 payload, status = e.read(), e.code 76 if status not in expect: 77 raise WalletError(f"HTTP {status} from {url}: " 78 f"{payload.decode(errors='replace')[:300]}") 79 if not payload: 80 return None 81 try: 82 return json.loads(payload) 83 except json.JSONDecodeError: 84 return payload.decode(errors="replace") 85 86 87 @dataclass 88 class BankAccount: 89 """A registered account at the demo bank.""" 90 91 username: str 92 password: str 93 bank: str = BANK 94 95 @property 96 def auth(self) -> tuple[str, str]: 97 return (self.username, self.password) 98 99 def balance(self) -> str: 100 info = _http("GET", f"{self.bank}/accounts/{self.username}", auth=self.auth) 101 bal = info.get("balance", {}) 102 sign = "-" if bal.get("credit_debit_indicator") == "debit" else "" 103 return f"{sign}{bal.get('amount', '?')}" 104 105 def start_withdrawal(self, amount: str) -> tuple[str, str]: 106 """Ask the bank for a withdrawal; returns (withdrawal id, taler URI).""" 107 res = _http("POST", f"{self.bank}/accounts/{self.username}/withdrawals", 108 body={"amount": amount}, auth=self.auth) 109 return res["withdrawal_id"], res["taler_withdraw_uri"] 110 111 def confirm_withdrawal(self, withdrawal_id: str, timeout: int = 90) -> None: 112 """Approve the withdrawal, the way the customer does in their banking app. 113 114 Two traps here, and each one costs a four-hundred-second timeout 115 somewhere else if it is not handled. 116 117 The endpoint lives under the account, not at the bank root: a POST to 118 `/withdrawals/<id>/confirm` answers 404 with "no endpoint defined for 119 the URL", which reads like the withdrawal is gone rather than like a 120 wrong path. 121 122 And it cannot be approved before the wallet has chosen an exchange for 123 it. `taler-wallet-cli withdraw` returns as soon as it has created the 124 transaction, which is a moment or two before that choice reaches the 125 bank, so an immediate confirmation gets a 409 -- and a 409 that is 126 quietly accepted leaves the withdrawal pending forever while the wallet 127 waits for a confirmation that never came. So this retries until the 128 bank takes it. 129 """ 130 url = (f"{self.bank}/accounts/{self.username}" 131 f"/withdrawals/{withdrawal_id}/confirm") 132 deadline = time.monotonic() + timeout 133 last = "" 134 while time.monotonic() < deadline: 135 try: 136 _http("POST", url, body={}, auth=self.auth, expect=(204, 200)) 137 return 138 except WalletError as e: 139 last = str(e) 140 if "409" not in last: 141 raise 142 time.sleep(2) 143 raise WalletError( 144 f"the bank would not confirm withdrawal {withdrawal_id} within " 145 f"{timeout}s; it is still waiting for the wallet to select an " 146 f"exchange: {last[:200]}") 147 148 149 def register_account(username: str, password: str, name: Optional[str] = None, 150 bank: str = BANK) -> BankAccount: 151 """Register a bank account, or adopt the existing one of the same name. 152 153 The demo bank allows registrations and asks for no TAN, so this needs no 154 operator involvement. A repeat registration answers 409, which is fine: 155 the harness wants *an* account by that name, not necessarily a new one -- 156 as long as the password still matches. A name somebody else (or an 157 earlier run with a different convention) already took does not, and the 158 401 only shows up on the next call, several steps away from the cause, so 159 the credential is checked here where it can still be explained. 160 """ 161 _http("POST", f"{bank}/accounts", 162 body={"username": username, "password": password, 163 "name": name or f"POS simulator {username}"}, 164 expect=(200, 204, 409)) 165 account = BankAccount(username=username, password=password, bank=bank) 166 try: 167 account.balance() 168 except WalletError as e: 169 if "401" not in str(e): 170 raise 171 raise WalletError( 172 f"the bank account {username!r} exists but this password does not " 173 f"open it -- pick another name, or pass the right password" 174 ) from e 175 return account 176 177 178 class Wallet: 179 """One `taler-wallet-cli` database, used as the customer's wallet. 180 181 Every call shells out. That is deliberate: the wallet under test is the 182 terminal, and keeping the customer in a separate process means nothing the 183 harness does to it can be mistaken for the terminal's own behaviour. 184 """ 185 186 def __init__(self, db: str | Path, cli: str = WALLET_CLI, 187 exchange: str = EXCHANGE): 188 self.db = Path(db) 189 self.cli = cli 190 self.exchange = exchange 191 self.db.parent.mkdir(parents=True, exist_ok=True) 192 193 # -- plumbing --------------------------------------------------------- 194 195 def run(self, *args: str, timeout: int = 300, 196 check: bool = True) -> subprocess.CompletedProcess: 197 # A ".json" database path makes the CLI pick its memory backend, which 198 # then refuses every command with "memory backend not supported"; the 199 # suffix is load-bearing, so it is asserted rather than hoped for. 200 if self.db.suffix != ".sqlite3": 201 raise WalletError(f"wallet db must end in .sqlite3, got {self.db}") 202 cmd = [self.cli, f"--wallet-db={self.db}", "--non-interactive", *args] 203 proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) 204 if check and proc.returncode != 0: 205 raise WalletError( 206 f"{' '.join(args)} failed ({proc.returncode}): " 207 f"{(proc.stderr or proc.stdout)[-800:]}") 208 return proc 209 210 def reset(self) -> None: 211 """Start from an empty wallet.""" 212 for suffix in ("", "-journal", "-wal", "-shm"): 213 p = Path(str(self.db) + suffix) 214 if p.exists(): 215 p.unlink() 216 217 # -- getting money ---------------------------------------------------- 218 219 def trust_exchange(self) -> None: 220 self.run("exchanges", "add", self.exchange, check=False) 221 self.run("exchanges", "accept-tos", self.exchange, check=False) 222 223 def withdraw(self, account: BankAccount, amount: str, 224 timeout: int = 420) -> None: 225 """Withdraw into this wallet, start to finish. 226 227 Three parties have to agree and the order matters. The bank creates 228 the operation; the wallet picks it up, chooses an exchange and 229 registers a reserve with the bank; only then can the account holder 230 approve it. 231 232 The middle step is the one that bites. `taler-wallet-cli withdraw` 233 returns as soon as the transaction exists, leaving it in 234 `pending:bank-register-reserve` -- and the wallet only makes progress 235 while one of its processes is running, so nothing advances it after 236 that command exits. Approving at that point gets "cannot confirm an 237 unselected withdrawal" forever. So the wallet is run again, waiting 238 for the state that means "your turn", and the approval goes after 239 that. 240 """ 241 self.trust_exchange() 242 wid, uri = account.start_withdrawal(amount) 243 self.run("withdraw", f"--uri={uri}", timeout=timeout) 244 if not self.wait_last(state="pending:bank-confirm-transfer", 245 timeout=min(timeout, 180)): 246 raise WalletError( 247 f"the wallet never got as far as asking for the withdrawal to " 248 f"be approved; it is in {self.state_of_last()!r}") 249 account.confirm_withdrawal(wid) 250 if not self.wait_last(timeout=timeout): 251 raise WalletError( 252 f"the withdrawal did not finish within {timeout}s; it is in " 253 f"{self.state_of_last()!r}") 254 255 def state_of_last(self) -> str: 256 """The newest transaction's state, for an error message worth reading.""" 257 out = self.run("transactions", "--oneline", "--pretty", 258 timeout=120, check=False).stdout 259 line = out.strip().splitlines()[0] if out.strip() else "" 260 import re 261 m = re.search(r"\[([^\]]+)\]", line) 262 return m.group(1) if m else (line[:120] or "unknown") 263 264 def balance(self) -> dict: 265 out = self.run("balance", timeout=120).stdout 266 try: 267 return json.loads(out) 268 except json.JSONDecodeError: 269 return {} 270 271 def available(self, currency: str) -> str: 272 for scope in self.balance().get("balances", []): 273 if scope.get("available", "").startswith(f"{currency}:"): 274 return scope["available"] 275 return f"{currency}:0" 276 277 def has_at_least(self, amount: str) -> bool: 278 """Whether the wallet can pay `amount`, comparing in minor units.""" 279 currency, value = amount.split(":", 1) 280 return _as_fraction(self.available(currency).split(":", 1)[1]) >= \ 281 _as_fraction(value) 282 283 # -- being a customer ------------------------------------------------- 284 285 def pay(self, pay_uri: str, timeout: int = 300) -> None: 286 """Scan the terminal's code and go through with the payment.""" 287 self.run("handle-uri", pay_uri, "--yes", timeout=timeout) 288 289 def claim_only(self, pay_uri: str) -> None: 290 """Look at the contract and stop there. 291 292 This is the state the terminal calls "claimed": the order is spoken for, 293 so it can no longer be deleted the ordinary way, and the payment screen 294 switches from "scan this" to "waiting for the customer to confirm". 295 `--inhibit` stops the wallet after it has the contract, which is 296 exactly where a hesitating customer stops. 297 """ 298 proc = subprocess.run( 299 [self.cli, f"--wallet-db={self.db}", "--non-interactive", 300 "--inhibit=pay", "handle-uri", pay_uri], 301 capture_output=True, text=True, timeout=180) 302 if proc.returncode != 0 and "inhibit" not in (proc.stderr or ""): 303 # Not fatal: the point is the order's state at the backend, which 304 # the caller checks. But a wallet that refused outright did not 305 # claim anything, and the scenario should say so rather than wait. 306 raise WalletError( 307 f"claim-only did not get as far as the contract: " 308 f"{(proc.stderr or proc.stdout)[-600:]}") 309 310 def accept_refund(self, refund_uri: str, timeout: int = 300) -> None: 311 """Take the refund the terminal is offering.""" 312 self.run("handle-uri", refund_uri, "--yes", timeout=timeout) 313 314 def abort_last(self) -> None: 315 self.run("transactions", "abort", "^", check=False) 316 317 def wait_last(self, state: str = "final", timeout: int = 300) -> bool: 318 """Block until the newest transaction settles; False on timeout.""" 319 proc = self.run("wait-tx", "^", "-s", state, timeout=timeout, check=False) 320 return proc.returncode == 0 321 322 def transactions(self) -> list[dict]: 323 out = self.run("transactions", "--json", timeout=120, check=False).stdout 324 try: 325 return json.loads(out).get("transactions", []) 326 except (json.JSONDecodeError, AttributeError): 327 return [] 328 329 330 def _as_fraction(value: str) -> int: 331 """A Taler amount's value as an integer number of 1e-8 units.""" 332 whole, _, frac = value.partition(".") 333 frac = (frac + "00000000")[:8] 334 return int(whole or 0) * 100_000_000 + int(frac) 335 336 337 def customer(name: str = "possim", password: Optional[str] = None, 338 db_dir: str = "/opt/taler-pos-sim/run/wallets") -> tuple[Wallet, BankAccount]: 339 """A funded-on-demand customer: a bank account and a wallet of its own. 340 341 The bank password is derived from the name so that a re-run adopts the same 342 account rather than failing to register a new one, and so that the 343 credential is not a secret worth protecting -- this is a demo bank holding 344 play money. 345 """ 346 password = password or f"{name}-pos-simulator" 347 account = register_account(name, password) 348 wallet = Wallet(Path(db_dir) / f"{name}.sqlite3") 349 return wallet, account 350 351 352 if __name__ == "__main__": 353 import sys 354 cmd = sys.argv[1] if len(sys.argv) > 1 else "info" 355 w, acct = customer(db_dir=os.environ.get("POS_WALLET_DIR", "/tmp/pos-sim-wallets")) 356 if cmd == "fund": 357 amount = sys.argv[2] if len(sys.argv) > 2 else "KUDOS:20" 358 print(f"bank balance before: {acct.balance()}") 359 w.withdraw(acct, amount) 360 print(f"wallet now holds {w.available(amount.split(':')[0])}") 361 elif cmd == "pay": 362 w.pay(sys.argv[2]) 363 print("paid") 364 else: 365 print(f"cli {w.cli}") 366 print(f"db {w.db}") 367 print(f"bank {acct.username} at {acct.bank}, balance {acct.balance()}") 368 print(f"wallet {w.balance().get('balances', [])}")