#!/usr/bin/env python3 """Glance client, Python standard library only. Inspect before running. Never sends funds. USDC quote.account_creation=payer-idempotent means ONE payment transaction: createAssociatedTokenAccountIdempotent (sender pays creation rent), transferChecked (exact atomic_amount, mint, token_account, decimals=6), then exact SPL Memo. Independently derive canonical_token_account from recipient/mint/token_program with an official Solana SDK and compare before signing. existing-only means the quoted noncanonical account must already exist; omit ATA creation. Sender pays ordinary SOL transaction fees separately. Receiver needs no prefunding or test transaction. This standard-library client prints the full structured invoice; use a wallet/SDK able to follow it, agree first, and never pay an expired invoice. Bitcoin quote.automatic_attribution=exact-unique-amount means atomic_amount sats is unique to the invoice: send exactly that amount as one output to recipient, fees on top. A different amount or late payment awaits protected attribution review. """ import argparse import hashlib import json import os from pathlib import Path import secrets import stat import sys import time from urllib.error import HTTPError from urllib.request import Request, build_opener, HTTPRedirectHandler BASE = 'https://glance.1puni.com' class NoRedirect(HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): return None # Never forward a private capability to another URL. def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--credential-file', type=Path, default=Path('.glance-capability')) parser.add_argument('--key', help='Stable retry key, 8..80 letters/digits/_/-. Use a new key for a later verification check.') parser.add_argument('action', choices=['methods','new','status','rail','agree','transaction','verify','project','ack','delete']) parser.add_argument('--ref') parser.add_argument('--rail', choices=['bitcoin','solana']) parser.add_argument('--txid') parser.add_argument('--project-file', type=Path, help='JSON containing six project fields and rail.') args = parser.parse_args() os.umask(0o077) action = args.action if action == 'methods': path, body = '/api/v1/methods', None elif action == 'new': if not args.rail: parser.error('--rail required') path, body = '/api/v1/inquiries', {'rail':args.rail} else: import re if not args.ref or not re.fullmatch('G-[0-9a-f]{16}',args.ref): parser.error('--ref must be a Glance reference') path = '/api/v1/intakes/' + args.ref if action == 'status': body = None else: path += '/' + {'agree':'agreement','verify':'verification','ack':'result-ack','delete':'deletion'}.get(action, action) body = {} if action == 'rail': if not args.rail: parser.error('--rail required') body = {'rail':args.rail} if action == 'transaction': if not args.txid: parser.error('--txid required') body = {'txid':args.txid} if action == 'project': if not args.project_file: parser.error('--project-file required') body = json.loads(args.project_file.read_text()) headers = {'Accept':'application/json'} if action != 'methods': if action == 'new' and not args.credential_file.exists(): fd = os.open(args.credential_file,os.O_WRONLY|os.O_CREAT|os.O_EXCL,0o600) with os.fdopen(fd,'w') as out: out.write(secrets.token_urlsafe(32)) # No symlink, group/world access or unbounded credential read. fd = os.open(args.credential_file,os.O_RDONLY|os.O_NOFOLLOW) with os.fdopen(fd) as source: info = os.fstat(source.fileno()) if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077 or info.st_size != 43: raise SystemExit('Credential file must be a regular private mode-0600 43-byte capability.') credential = source.read(44) headers['Authorization'] = 'Bearer '+credential encoded = None if body is None else json.dumps(body,sort_keys=True,separators=(',',':')).encode() if encoded is not None: headers['Content-Type'] = 'application/json' headers['Idempotency-Key'] = args.key or hashlib.sha256(path.encode()+b'\n'+encoded).hexdigest() # A release restart can briefly return proxy 502/503/504 or refuse connections. # Retrying the identical request and Idempotency-Key is safe; service JSON # answers (including 503 for an unavailable rail) are final. for attempt, pause in enumerate((2, 4, 8, 15, 30, 0)): request = Request(BASE+path,data=encoded,headers=headers) try: with build_opener(NoRedirect()).open(request,timeout=15) as response: print(json.dumps(json.load(response),indent=2)) return 0 except HTTPError as error: raw = error.read(1200) try: json.loads(raw) transient = False except ValueError: transient = error.code in (502,503,504) if transient and pause: time.sleep(pause); continue # Output bounded public response only, never request headers/credentials. print('HTTP '+str(error.code),file=sys.stderr) print(raw.decode('utf-8',errors='replace'),file=sys.stderr) return 1 except Exception: if pause: time.sleep(pause); continue print('Request unavailable after retries. Retry the same action, arguments and key later; do not pay again.',file=sys.stderr) return 1 if __name__ == '__main__': sys.exit(main())