162 lines
8.2 KiB
Python
162 lines
8.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Read-only legacy asset inventory. Never guesses refunds or writes game tables."""
|
|
import argparse
|
|
from collections import Counter
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
import xml.etree.ElementTree as ET
|
|
|
|
TABLES = ('player', 'item', 'offline_shop_npc', 'offline_shop_item',
|
|
'offline_shop_log', 'offline_shop_log_important', 'port_economy_custody',
|
|
'port_economy_listings', 'port_economy_orders', 'port_economy_credit')
|
|
REQUIRED = {'player', 'item', 'offline_shop_item', 'offline_shop_npc',
|
|
'offline_shop_log', 'offline_shop_log_important'}
|
|
|
|
|
|
def canonical(value):
|
|
return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode()
|
|
|
|
|
|
def digest(value):
|
|
return hashlib.sha256(canonical(value)).hexdigest()
|
|
|
|
|
|
def xml_rows(output):
|
|
text = re.sub(r'<\?xml[^?]*\?>', '', output)
|
|
root = ET.fromstring('<results>' + text + '</results>')
|
|
return [[{f.attrib['name']: None if f.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}nil') == 'true' else (f.text or '') for f in row} for row in result.findall('row')]
|
|
for result in root.findall('resultset')]
|
|
|
|
|
|
def snapshot(defaults, database):
|
|
if not re.fullmatch(r'[A-Za-z0-9_]+', database):
|
|
raise ValueError('invalid database name')
|
|
def query(sql):
|
|
# Credentials remain in the supplied protected MySQL defaults file.
|
|
result = subprocess.run(['mysql', '--defaults-extra-file=' + str(defaults.resolve()),
|
|
'--xml', '--database=' + database, '--execute=' + sql],
|
|
check=True, capture_output=True)
|
|
return xml_rows(result.stdout.decode('utf-8'))
|
|
metadata = query("SELECT TABLE_NAME,COLUMN_NAME FROM information_schema.columns "
|
|
"WHERE TABLE_SCHEMA=DATABASE() ORDER BY TABLE_NAME,ORDINAL_POSITION")[0]
|
|
columns = {}
|
|
for row in metadata:
|
|
if row['TABLE_NAME'] in TABLES:
|
|
columns.setdefault(row['TABLE_NAME'], []).append(row['COLUMN_NAME'])
|
|
if not REQUIRED <= columns.keys():
|
|
raise ValueError('required legacy tables missing: ' + ','.join(sorted(REQUIRED - columns.keys())))
|
|
engines = query("SELECT TABLE_NAME,ENGINE FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE()")[0]
|
|
nontransactional = [r['TABLE_NAME'] for r in engines if r['TABLE_NAME'] in columns and r['ENGINE'] != 'InnoDB']
|
|
if nontransactional:
|
|
raise ValueError('consistent snapshot requires InnoDB: ' + ','.join(nontransactional))
|
|
sql = ['SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ',
|
|
'START TRANSACTION WITH CONSISTENT SNAPSHOT']
|
|
for table, names in columns.items():
|
|
# Hex every value, including arbitrary binary metadata and names. NULL
|
|
# stays NULL; all original columns survive the review snapshot.
|
|
def ident(name):
|
|
return '`' + name.replace('`', '``') + '`'
|
|
sql.append('SELECT ' + ','.join('HEX(CAST(' + ident(n) + ' AS BINARY)) AS ' + ident(n) for n in names) +
|
|
' FROM ' + ident(table))
|
|
sql.append('COMMIT')
|
|
results = query(';'.join(sql))
|
|
if len(results) != len(columns):
|
|
raise ValueError('incomplete snapshot')
|
|
tables = dict(zip(columns, results))
|
|
# SELECT order is unspecified. Stable snapshots sort by complete row bytes.
|
|
for rows in tables.values():
|
|
rows.sort(key=canonical)
|
|
payload = {'format': 1, 'encoding': 'mysql-hex-all-columns', 'tables': tables}
|
|
return dict(payload, sha256=digest(payload))
|
|
|
|
|
|
def audit(snap):
|
|
payload = {k: v for k, v in snap.items() if k != 'sha256'}
|
|
if snap.get('format') != 1 or snap.get('encoding') != 'mysql-hex-all-columns' or digest(payload) != snap.get('sha256'):
|
|
raise ValueError('snapshot format or checksum mismatch')
|
|
if not REQUIRED <= snap['tables'].keys():
|
|
raise ValueError('incomplete legacy snapshot')
|
|
def rows(table):
|
|
return [{k: bytes.fromhex(v).decode('utf-8', 'surrogateescape') if v is not None else None
|
|
for k, v in row.items()} for row in snap['tables'].get(table, [])]
|
|
def number(row, key, maximum=2**32-1):
|
|
value = row.get(key)
|
|
if value is None or not re.fullmatch(r'[0-9]+', value) or int(value) > maximum:
|
|
raise ValueError('invalid ' + key)
|
|
return int(value)
|
|
players = rows('player')
|
|
ids = Counter(r.get('id') for r in players)
|
|
owners = {r.get('id') for r in players if ids[r.get('id')] == 1}
|
|
normal = Counter(r.get('id') for r in rows('item'))
|
|
custody = Counter(r.get('id') for r in rows('port_economy_custody'))
|
|
legacy = rows('offline_shop_item')
|
|
duplicates = Counter(r.get('id') for r in legacy)
|
|
assets = []
|
|
for row in legacy:
|
|
reasons = []
|
|
try:
|
|
item = number(row, 'id'); owner = number(row, 'owner_id')
|
|
if not item or not owner or not number(row, 'count', 2000) or not number(row, 'vnum'):
|
|
reasons.append('invalid_item')
|
|
if number(row, 'price', 2_000_000_000_000_000) == 0:
|
|
reasons.append('invalid_price')
|
|
except ValueError:
|
|
reasons.append('invalid_numeric_fields')
|
|
if duplicates[row.get('id')] != 1:
|
|
reasons.append('duplicate_legacy_id')
|
|
if normal[row.get('id')] or custody[row.get('id')]:
|
|
reasons.append('item_id_exists_elsewhere')
|
|
if row.get('owner_id') not in owners:
|
|
reasons.append('owner_missing_or_duplicate')
|
|
extra = row.get('port_extra')
|
|
if extra is None or len(extra.encode('utf-8', 'surrogateescape')) != 69:
|
|
reasons.append('missing_or_invalid_full_item_metadata')
|
|
if row.get('status') != '0':
|
|
reasons.append('historical_order_requires_delivery_payment_evidence')
|
|
# A structurally valid row is only a candidate. It is never an approved
|
|
# migration: legacy statuses cannot prove ownership or refund liability.
|
|
assets.append({'key': 'legacy-item:' + str(row.get('id')), 'row_sha256': digest(row),
|
|
'classification': 'quarantine' if reasons else 'custody_review',
|
|
'reasons': reasons, 'action': 'manual_evidence_review'})
|
|
for row in players:
|
|
if row.get('shop_money') not in (None, '0'):
|
|
reasons = []
|
|
try:
|
|
number(row, 'shop_money', 2_000_000_000_000_000)
|
|
except ValueError:
|
|
reasons.append('invalid_balance')
|
|
assets.append({'key': 'legacy-proceeds:' + str(row.get('id')), 'row_sha256': digest(row),
|
|
'classification': 'quarantine' if reasons else 'proceeds_review',
|
|
'reasons': reasons, 'action': 'reconcile_logs_before_transfer'})
|
|
history = {t: len(snap['tables'].get(t, [])) for t in ('offline_shop_log', 'offline_shop_log_important')}
|
|
return {'format': 1, 'snapshot_sha256': snap['sha256'], 'assets': assets,
|
|
'history_rows': history, 'automatic_refunds': [], 'automatic_writes': [],
|
|
'release_gate': 'BLOCKED_PENDING_RECONCILIATION',
|
|
'required_review': 'Resolve every asset against original item metadata, owners, payments, deliveries and logs; missing evidence stays quarantined.'}
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
sub = parser.add_subparsers(dest='command', required=True)
|
|
export = sub.add_parser('snapshot')
|
|
export.add_argument('--defaults-file', type=Path, required=True)
|
|
export.add_argument('--database', required=True)
|
|
export.add_argument('--output', type=Path, required=True)
|
|
inspect = sub.add_parser('audit')
|
|
inspect.add_argument('--snapshot', type=Path, required=True)
|
|
inspect.add_argument('--output', type=Path, required=True)
|
|
args = parser.parse_args()
|
|
result = snapshot(args.defaults_file, args.database) if args.command == 'snapshot' else audit(json.loads(args.snapshot.read_text()))
|
|
# Refuse replacement of prior evidence; owner-only permissions for asset data.
|
|
with os.fdopen(os.open(args.output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w') as out:
|
|
out.write(json.dumps(result, indent=2, ensure_ascii=True) + '\n')
|
|
print(args.command + ' complete; no game tables modified')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|