"""Upload, quote, pay for and collect one chosen cost-basis workpaper. Python 3, standard library.""" import argparse import base64 import hashlib import http.client import json import os from pathlib import Path import re import secrets import sys import tempfile import time from datetime import datetime, timedelta HOST = 'bulk---chainiq-fifo-hpdt6vofhq-ue.a.run.app' ORIGIN = 'https://' + HOST UPLOADS = '/api/v1/bulk/uploads' CHECKOUT = '/api/v1/calculate-tax' RECOVERY = '/api/v1/result' CHUNK = 4 * 1024 * 1024 MAX_BYTES = 32 * 1024 * 1024 TOKEN = '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913' MERCHANT = '0xed6b743f9a993d7b813deef3d479cac6804f958a' NONCE = 'chainiq-x402-operation-nonce-v1' NETWORK = 'eip155:8453' METHODS = ('FIFO', 'LIFO', 'HIFO', 'OPTIMIZED_HIFO') STATEMENT_ORDER = 'chainiq.statement-2025-order.v1' STATEMENT_DOWNLOAD = 'chainiq.statement-2025-download.v1' BUNDLE = 'fifo-statement-2025-v1' ADDON = 'fifo-statement-2025-paid-csv-v1' def schema(method, kind): return 'chainiq.bulk-' + ('fifo' if method == 'FIFO' else 'method') + '-' + kind + '.v1' def canonical(value): return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False, allow_nan=False).encode() def sha(raw): return hashlib.sha256(raw).hexdigest() def request(path, body, *, key=None, media='application/json', agent='ChainIQ-supplied-client/1', extra=None): conn = http.client.HTTPSConnection(HOST, timeout=60) headers = {'Content-Type':media,'User-Agent':agent,'Accept-Encoding':'identity', **(extra or {})} if key is not None: headers['chainiq-result-key'] = key try: conn.request('POST', path, body=body, headers=headers) response = conn.getresponse() raw = response.read(CHUNK + 1) if len(raw) > CHUNK: raise ValueError('Unexpected response size') return response.status, {k.lower():v for k,v in response.getheaders()}, raw finally: conn.close() def json_post(path, value, *, key, agent): code, _, raw = request(path, canonical(value), key=key, agent=agent) data = json.loads(raw) if code not in (200,202): raise ValueError('HTTP '+str(code)+' '+str(data.get('error','upload failed'))) return data def save(path, value): # An interrupted write must never replace a recovery key or publish a partial order. with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as file: temporary = Path(file.name) try: file.write(canonical(value)) file.flush() os.fsync(file.fileno()) os.link(temporary, path) finally: temporary.unlink() def prior_purchase(state): packet, saved, _ = read_state(state) receipt = json.loads((state/'receipt.json').read_bytes()) return packet['request'], saved['key'], dict(payer=receipt['payer'],paymentID=packet['paymentID']) def prepare(source, state, *, method=None, agent='ChainIQ-supplied-client/1', wait_seconds=540, statement_inventory=None, replaces=None, paid_csv=None): if not 0 < source.stat().st_size <= MAX_BYTES: raise ValueError('Supply a JSON file of at most 32 MiB') raw = source.read_bytes() book = json.loads(raw) fills = len(book['trades']) if method is not None and ('method' in book and book['method'] != method): raise ValueError('The selected method differs from the method in the supplied file') method = book.get('method', method if method is not None else 'FIFO') selection, inherited_key = None, None if statement_inventory is not None: if (not re.fullmatch('[A-Za-z0-9._-]{1,48}',statement_inventory) or method!='FIFO' or book.get('taxYear')!=2025 or book.get('inventoryRef',statement_inventory)!=statement_inventory): raise ValueError('Use FIFO, tax year 2025 and a stable inventory label matching inventoryRef when present') selection = dict(generation='corrected' if replaces else 'original',inventory=statement_inventory) if replaces: parent,inherited_key,proof=prior_purchase(replaces) if parent.get('schema')!=STATEMENT_ORDER or parent['inventory']!=statement_inventory: raise ValueError('Use the paid prior statement for this inventory') selection['replaces']=dict(proof,orderSHA256=sha(canonical(parent))) if paid_csv: prior,key,proof=prior_purchase(paid_csv) if prior.get('schema')!=schema('FIFO','order') or (inherited_key and inherited_key!=key): raise ValueError('Use the paid FIFO workpaper with the same private recovery key') inherited_key=key selection['csvPurchase']=proof elif replaces or paid_csv: raise ValueError('Select --statement-2025 INVENTORY for PDF options') if not 1 <= fills <= 200_000 or book.get('authorized') is not True or method not in METHODS: raise ValueError('Supply 1–200,000 authorized spot fills and one supported lot method') if method != 'FIFO' and 'method' not in book: book['method'] = method raw = canonical(book) if len(raw) > MAX_BYTES: raise ValueError('The prepared trade JSON exceeds 32 MiB') os.umask(0o077) state.mkdir(mode=0o700, exist_ok=True) target = state/'recovery.json' if not target.exists(): identity=dict(key=inherited_key or secrets.token_hex(32),paymentID='bulk_'+secrets.token_hex(16),sourceSHA256=sha(raw),method=method) if selection: identity['statement']=selection save(target,identity) saved = json.loads(target.read_bytes()) if (saved['sourceSHA256'] != sha(raw) or saved.get('method','FIFO') != method or saved.get('statement')!=selection or (inherited_key and saved['key']!=inherited_key)): raise ValueError('Use the original source file and lot method for this recovery directory') key = saved['key'] key_hash = sha(bytes.fromhex(key)) if book.get('resultKeySHA256',key_hash) != key_hash: raise ValueError('This source has a different recovery key binding') parts = [raw[i:i+CHUNK] for i in range(0,len(raw),CHUNK)] manifest = dict(schema=schema(method,'upload'),authorized=True,method=method,fills=fills, byteLength=len(raw),sha256=sha(raw),resultKeySHA256=key_hash,parts=[sha(p) for p in parts]) started = json_post(UPLOADS,manifest,key=key,agent=agent) if started['upload'] != sha(canonical(manifest)) or started['partBytes'] != CHUNK: raise ValueError('Upload identity changed') path = UPLOADS+'/'+started['upload'] status = json_post(path+'/status',{},key=key,agent=agent) for index in status.get('missing', []): code, _, reply = request(path+'/parts/'+str(index),parts[index],key=key,media='application/octet-stream',agent=agent) if code != 200 or json.loads(reply).get('sha256') != manifest['parts'][index]: raise ValueError('Part '+str(index)+' failed (HTTP '+str(code)+')') status = json_post(path+'/submit',{},key=key,agent=agent) deadline = time.monotonic()+wait_seconds while status.get('status') == 'processing' and time.monotonic() maximum or method not in METHODS or ready['schema'] != expected_schema or ready['method'] != method or not 1 <= ready['fills'] <= 200_000 or not re.fullmatch(r'[0-9a-f]{64}',ready['engine']) or ready['resultKeySHA256'] != sha(bytes.fromhex(saved['key'])) or packet['paymentID'] != saved['paymentID'] or bound != {'requestSHA256':sha(canonical(ready)),'engineVersion':ready['engine']} or offer['extensions']['payment-identifier']['info'].get('required') is not True): raise ValueError('Offer differs from the selected workpaper or the published Base USDC payment terms') return term def read_state(state): packet = json.loads((state/'quote.json').read_bytes()) saved = json.loads((state/'recovery.json').read_bytes()) return packet, saved, checked_terms(packet,saved) def atomic_amount(amount): if not re.fullmatch(r'(0|[1-9][0-9]{0,2})(\.[0-9]{1,6})?',amount): raise ValueError('Use the exact USDC price with at most six decimal places') whole, _, fraction = amount.partition('.') return str(int(whole)*1_000_000 + int(fraction.ljust(6,'0'))) def typed_data(packet, term, payer, approved, deadline): payer = payer.lower() if not re.fullmatch(r'0x[0-9a-f]{40}',payer) or payer in (MERCHANT,'0x'+'0'*40) or approved != term['amount']: raise ValueError('Payer or explicitly approved amount differs from this offer') ready = packet['request'] operation = dict(payer=payer,payment_id=packet['paymentID'],network=NETWORK,asset=TOKEN,pay_to=MERCHANT, scheme='exact',engine_version=ready['engine'],request_sha256=sha(canonical(ready)), amount_atomic=approved,endpoint=CHECKOUT,resource_url=ORIGIN+CHECKOUT, fill_count=str(ready['fills']),price_schedule=ready.get('priceSchedule','higher')) nonce = '0x'+sha(canonical([NONCE,ORIGIN+CHECKOUT,sha(canonical(operation))])) def fields(items): return [dict(name=name,type=kind) for name,kind in items] return { 'types': { 'EIP712Domain': fields([('name','string'),('version','string'),('chainId','uint256'),('verifyingContract','address')]), 'TransferWithAuthorization': fields([('from','address'),('to','address'),('value','uint256'), ('validAfter','uint256'),('validBefore','uint256'),('nonce','bytes32')])}, 'primaryType': 'TransferWithAuthorization', 'domain': dict(name='USD Coin',version='2',chainId=8453,verifyingContract=term['asset']), 'message': {'from':payer,'to':term['payTo'],'value':approved,'validAfter':'0','validBefore':str(deadline),'nonce':nonce}} def authorize(state, payer, amount): packet, _, term = read_state(state) output = state/'typed-data.json' typed = typed_data(packet,term,payer,atomic_amount(amount),int(time.time()) + 60) if (state/'submitted.json').exists() and json.loads((state/'submitted.json').read_bytes()) != { 'payer':typed['message']['from'],'nonce':typed['message']['nonce']}: raise ValueError('This order already has another payer or transfer nonce.') # Regeneration keeps the payer, order and transfer nonce fixed. if output.exists(): prior = json.loads(output.read_bytes()) if prior['message']['from'] != typed['message']['from']: raise ValueError('Use the original payer for this order') if int(prior['message']['validBefore']) > time.time() and prior == typed_data( packet,term,payer,term['amount'],prior['message']['validBefore']): return output output.unlink() save(output,typed) return output def pay(state, signature_file, *, retry=False): packet, _, term = read_state(state) typed = json.loads((state/'typed-data.json').read_bytes()) auth = typed['message'] if (typed != typed_data(packet,term,auth['from'],term['amount'],auth['validBefore']) or not time.time() < int(auth['validBefore']) <= time.time()+61): raise ValueError('Signing request expired or changed. Generate fresh typed data before signing.') signature = signature_file.read_text().strip() if not re.fullmatch(r'0x[0-9a-fA-F]{130}',signature): raise ValueError('Supply a text file containing only the 65-byte EIP-712 signature') offer = packet['offer'] ext = dict(offer['extensions']) identifier = ext['payment-identifier'] ext['payment-identifier'] = dict(identifier,info=dict(identifier['info'],id=packet['paymentID'])) payment = dict(x402Version=2,resource=offer['resource'],accepted=term,extensions=ext, payload=dict(authorization=auth,signature=signature)) submitted = state/'submitted.json' identity = dict(payer=auth['from'],nonce=auth['nonce']) if submitted.exists(): if not retry or json.loads(submitted.read_bytes()) != identity: raise ValueError('This order was already submitted. Use collect first. An explicit retry requires the same payer and nonce.') else: save(submitted,identity) code, _, raw = request(CHECKOUT,canonical(packet['request']), extra={'payment-signature':base64.b64encode(canonical(payment)).decode('ascii')}) if code not in (200,202): raise ValueError('Payment submission returned HTTP '+str(code)+'. Check the original order with collect.') return code def collect(state, output, transaction=None): packet, saved, term = read_state(state) sent = json.loads((state/'submitted.json').read_bytes()) order = dict(request=packet['request'],payer=sent['payer'],paymentID=packet['paymentID']) nonce = typed_data(packet,term,sent['payer'],term['amount'],0)['message']['nonce'] extra = {} if transaction: if not re.fullmatch(r'0x[0-9a-fA-F]{64}',transaction): raise ValueError('Expected the Base transaction hash') extra['chainiq-settlement-transaction'] = transaction code, headers, raw = request(RECOVERY,canonical(order),key=saved['key'],extra=extra) if code == 202: return False if code != 200: raise ValueError('Result lookup returned HTTP '+str(code)) receipt = json.loads(base64.b64decode(headers['chainiq-result-receipt'],validate=True)) info = receipt['extensions']['chainiq-result-v1'] times = [datetime.fromisoformat(info[key].replace('Z','+00:00')) for key in ('confirmedAt','expiresAt')] manifest = json.loads(raw) pdf = bool(saved.get('statement')) kind = 'pdfSHA256' if pdf else 'csvSHA256' if pdf and (manifest.get('mimeType')!='application/pdf' or manifest.get('taxYear')!=2025 or any(manifest.get(k)!=packet['request'][k] for k in ('pdfSHA256','csvSHA256','generation','replaces','allocations'))): raise ValueError('Statement manifest differs from the purchased PDF') if (receipt['success'] is not True or receipt['network'] != NETWORK or receipt['payer'].lower() != sent['payer'] or receipt['amount'] != term['amount'] or not re.fullmatch(r'0x[0-9a-f]{64}',receipt['transaction']) or sent['nonce'] != nonce or info['authorizationNonce'] != nonce or info['resultSHA256'] != sha(raw) or type(info['eventIndex']) is not int or info['eventIndex'] < 0 or times[1]-times[0] != timedelta(hours=1) or manifest['schema'] != (STATEMENT_DOWNLOAD if pdf else schema(order['request']['method'],'download')) or manifest['orderSHA256'] != sha(canonical(order['request'])) or (manifest['method'],manifest['fills']) != (order['request']['method'],order['request']['fills']) or not 0 < manifest['bytes'] <= 16*1024*1024 or len(manifest['parts']) != (manifest['bytes']+CHUNK-1)//CHUNK or not re.fullmatch(r'[0-9a-f]{64}',manifest[kind])): raise ValueError('Payment receipt or download manifest differs from this order') receipt_path = state/'receipt.json' if not receipt_path.exists(): save(receipt_path,receipt) elif json.loads(receipt_path.read_bytes()) != receipt: raise ValueError('Settlement receipt changed') if output.exists(): if output.stat().st_size == manifest['bytes'] and sha(output.read_bytes()) == manifest[kind]: return True raise ValueError('Choose a new output path. The existing file differs.') digest = hashlib.sha256() with tempfile.NamedTemporaryFile(dir=output.parent,delete=False) as file: temporary = Path(file.name) try: for i, part in enumerate(manifest['parts']): expected = min(CHUNK,manifest['bytes']-i*CHUNK) if part['bytes'] != expected or not re.fullmatch(r'[0-9a-f]{64}',part['sha256']): raise ValueError('Invalid download part') cached = state/(('pdf-part-' if pdf else 'csv-part-')+str(i)) if cached.exists(): data = cached.read_bytes() else: code, _, data = request(RECOVERY,canonical(dict(order,part=i)),key=saved['key']) if code != 200: raise ValueError('Part '+str(i)+' returned HTTP '+str(code)+'. Rerun collect to resume.') if len(data) != expected or sha(data) != part['sha256']: raise ValueError('Download part failed verification') if not cached.exists(): with tempfile.NamedTemporaryFile(dir=state,delete=False) as cache: cache.write(data) os.replace(cache.name,cached) file.write(data) digest.update(data) if digest.hexdigest() != manifest[kind]: raise ValueError('CSV digest differs from receipt manifest') file.flush() os.fsync(file.fileno()) os.link(temporary,output) finally: temporary.unlink() return True def main(): parser = argparse.ArgumentParser(description=__doc__) commands = parser.add_subparsers(dest='action',required=True) start = commands.add_parser('prepare',help='Upload or resume, then save an unsigned x402 quote') start.add_argument('trades',type=Path) start.add_argument('--method',choices=METHODS,help='Choose the lot method. An explicit method in the trade file must match.') start.add_argument('--statement-2025',metavar='INVENTORY',help='Prepare an optional 2025 FIFO gain/loss PDF for this inventory') start.add_argument('--replaces',type=Path,help='Paid prior PDF state directory for a correction') start.add_argument('--paid-csv',type=Path,help='Paid FIFO CSV state for this same input to charge only the PDF premium') sign = commands.add_parser('authorize',help='Create EIP-712 data for your existing wallet to sign') sign.add_argument('--payer',required=True) sign.add_argument('--amount-usdc',required=True,help='Exact price you authorize, for example 45.00') send = commands.add_parser('pay',help='Submit one wallet signature for this order') send.add_argument('--signature-file',type=Path,required=True) send.add_argument('--retry-same-order',action='store_true',help='Explicitly retry this order after a failed submission, using its original payer and transfer nonce') get = commands.add_parser('collect',help='Recover and verify the purchased CSV without paying again') get.add_argument('--output',type=Path,required=True) get.add_argument('--transaction',help='Optional hash of the original payment on Base') for sub in (start,sign,send,get): sub.add_argument('--state',type=Path,required=True,help='Private recovery directory for this order') argv = sys.argv[1:] if argv and not argv[0].startswith('-') and argv[0] not in commands.choices: argv.insert(0,'prepare') args = parser.parse_args(argv) os.umask(0o077) if args.action == 'prepare': quote = prepare(args.trades,args.state,method=args.method,statement_inventory=args.statement_2025,replaces=args.replaces,paid_csv=args.paid_csv) print('Unsigned offer saved. Exact price in millionths of USDC:',quote['offer']['accepts'][0]['amount']) elif args.action == 'authorize': print('Sign with your payer wallet using eth_signTypedData_v4:',authorize(args.state,args.payer,args.amount_usdc)) elif args.action == 'pay': print('Payment submitted (HTTP '+str(pay(args.state,args.signature_file,retry=args.retry_same_order))+'). Use collect to retrieve your file.') elif collect(args.state,args.output,args.transaction): print('Verified file:',args.output) else: print('Settlement pending. Rerun collect with this order.') if __name__ == '__main__': try: main() except (ValueError,OSError,KeyError) as error: sys.exit(str(error))