feat(server): save economy hardening and CH5 continuation work
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Plan/apply gold columns from the actual selected schemas; never truncate balances."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
MAXIMUM=2000000000000000
|
||||
|
||||
|
||||
def validate_column(kind):
|
||||
if not re.fullmatch(r'(tinyint|smallint|mediumint|int|bigint)(\(\d+\))?( unsigned)?',kind.lower()):
|
||||
raise ValueError('Unexpected money column definition: '+kind)
|
||||
|
||||
|
||||
def fingerprint(value):
|
||||
return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
|
||||
|
||||
|
||||
def save(path,value):
|
||||
temporary=path.with_name(path.name+'.new')
|
||||
with temporary.open('x') as out:
|
||||
os.chmod(temporary,0o600);json.dump(value,out,indent=2);out.write('\n');out.flush();os.fsync(out.fileno())
|
||||
os.replace(temporary,path)
|
||||
fd=os.open(path.parent,os.O_RDONLY)
|
||||
try:os.fsync(fd)
|
||||
finally:os.close(fd)
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument('--player',required=True);p.add_argument('--log',required=True)
|
||||
p.add_argument('--plan',type=Path,required=True);p.add_argument('--apply',action='store_true')
|
||||
p.add_argument('--offline',action='store_true');p.add_argument('--backup-id')
|
||||
a=p.parse_args()
|
||||
if not all(re.fullmatch(r'[A-Za-z0-9_]+',s) for s in (a.player,a.log)):p.error('Invalid schema name')
|
||||
if a.apply and (not a.offline or not a.backup_id):p.error('Apply requires --offline --backup-id')
|
||||
def sql(query):
|
||||
r=subprocess.run(['mysql','-N','-B'],input=query,text=True,capture_output=True,check=True)
|
||||
return [line.split('\t') for line in r.stdout.splitlines()]
|
||||
identity=sql('SELECT @@hostname,@@port,@@server_id,@@version;')
|
||||
if len(identity)!=1:raise RuntimeError('Unknown server identity')
|
||||
required=[(a.player,t,'gold',True) for t in ('player','player_deleted','safebox','guild')]+[(a.log,'money_log','gold',False)]
|
||||
optional=[(a.log,'log','what',False)]+[(a.player,t,c,False) for t,c in [('player','shop_money'),('offline_shop_item','price'),('offline_shop_log','price'),('offline_shop_log_important','price')]]
|
||||
rows=[];ddl={}
|
||||
for schema,table,column,unsigned in required+optional:
|
||||
definition=sql("SELECT COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA FROM information_schema.columns WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME='%s';"%(schema,table,column))
|
||||
if len(definition)!=1:
|
||||
if (schema,table,column,unsigned) in optional:continue
|
||||
raise RuntimeError('Missing required column: '+'.'.join((schema,table,column)))
|
||||
validate_column(definition[0][0])
|
||||
if definition[0][3]:raise RuntimeError('Generated/automatic money columns require explicit review')
|
||||
target='bigint(20)'+(' unsigned' if unsigned else '')
|
||||
upper=(2**63-1) if schema==a.log else MAXIMUM
|
||||
lower=-(2**63) if schema==a.log else 0
|
||||
invalid=sql('SELECT COUNT(*) FROM `%s`.`%s` WHERE `%s` IS NULL OR `%s`>%d OR `%s`<%d;'%(schema,table,column,column,upper,column,lower))
|
||||
if invalid!=[['0']]:raise RuntimeError('Out of range/null money data: '+schema+'.'+table+'.'+column)
|
||||
key=schema+'.'+table
|
||||
if key not in ddl:ddl[key]=sql('SHOW CREATE TABLE `%s`.`%s`;'%(schema,table))
|
||||
rows.append({'schema':schema,'table':table,'column':column,'before':definition[0],'target':target})
|
||||
if a.plan.exists():
|
||||
plan=json.loads(a.plan.read_text());checksum=plan.get('sha256');base={k:v for k,v in plan.items() if k!='sha256'}
|
||||
if plan.get('version')!=1 or plan.get('identity')!=identity[0] or checksum!=fingerprint(base):raise RuntimeError('Foreign/stale/corrupt plan')
|
||||
if [(r['schema'],r['table'],r['column']) for r in rows]!=[(r['schema'],r['table'],r['column']) for r in plan['columns']]:raise RuntimeError('Column inventory differs from plan')
|
||||
for current,bound in zip(rows,plan['columns']):
|
||||
if current['before']!=bound['before'] and current['before'][:2]!=[bound['target'],'NO']:raise RuntimeError('Column changed since planning')
|
||||
else:
|
||||
plan={'version':1,'identity':identity[0],'columns':rows,'show_create':ddl};plan['sha256']=fingerprint(plan)
|
||||
a.plan.parent.mkdir(parents=True,exist_ok=True);save(a.plan,plan)
|
||||
if not a.apply:
|
||||
print('PLAN ONLY: review '+str(a.plan));return
|
||||
for row in plan['columns']:
|
||||
sql('ALTER TABLE `%s`.`%s` MODIFY COLUMN `%s` %s NOT NULL DEFAULT 0;'%(row['schema'],row['table'],row['column'],row['target']))
|
||||
actual=sql("SELECT COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT FROM information_schema.columns WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME='%s';"%(row['schema'],row['table'],row['column']))
|
||||
if actual!=[[row['target'],'NO','0']]:raise RuntimeError('Money column post-validation failed')
|
||||
save(a.plan.with_name(a.plan.name+'.receipt.json'),{'plan_sha256':plan['sha256'],'backup_id':a.backup_id,'verified':True})
|
||||
print('PASS: columns verified; balances preserved. Runtime release acceptance is separate.')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -1,14 +1,4 @@
|
||||
-- Metin2 64-bit Gold Migration Script
|
||||
-- Target: player database (player, safebox, guild)
|
||||
-- GOLD_MAX_64 = 2,000,000,000,000,000 (2 quadrillion / 2000万亿)
|
||||
|
||||
USE `player`;
|
||||
|
||||
-- 1. Upgrade player.gold to BIGINT(20) UNSIGNED
|
||||
ALTER TABLE `player` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;
|
||||
|
||||
-- 2. Upgrade safebox.gold to BIGINT(20) UNSIGNED
|
||||
ALTER TABLE `safebox` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;
|
||||
|
||||
-- 3. Upgrade guild.gold to BIGINT(20) UNSIGNED
|
||||
ALTER TABLE `guild` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;
|
||||
-- Blind DDL cannot verify schema identity, player_deleted, or the actual money_log.
|
||||
-- Use migrate_gold64.py --player SCHEMA --log LOG_SCHEMA --plan PATH.
|
||||
-- Apply the reviewed plan with --apply --offline --backup-id BACKUP.
|
||||
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Use the source-bound gold migration planner; blind DDL is disabled';
|
||||
|
||||
@@ -1,19 +1,4 @@
|
||||
-- Metin2 64-bit Gold Rollback Script
|
||||
-- Target: player database (player, safebox, guild)
|
||||
-- Restores gold column to INT(11) with clamp to 2,000,000,000 to prevent data truncation errors
|
||||
|
||||
USE `player`;
|
||||
|
||||
-- 1. Clamp values exceeding 2,000,000,000 before downcasting
|
||||
UPDATE `player` SET `gold` = 2000000000 WHERE `gold` > 2000000000;
|
||||
UPDATE `safebox` SET `gold` = 2000000000 WHERE `gold` > 2000000000;
|
||||
UPDATE `guild` SET `gold` = 2000000000 WHERE `gold` > 2000000000;
|
||||
|
||||
-- 2. Restore player.gold to INT(11) NOT NULL DEFAULT 0
|
||||
ALTER TABLE `player` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;
|
||||
|
||||
-- 3. Restore safebox.gold to INT(11) NOT NULL DEFAULT 0
|
||||
ALTER TABLE `safebox` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;
|
||||
|
||||
-- 4. Restore guild.gold to INT(11) NOT NULL DEFAULT 0
|
||||
ALTER TABLE `guild` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;
|
||||
-- Asset-preserving rollback: keep the expanded schema and every balance.
|
||||
-- Deploy a compatible binary that reads/writes BIGINT while disabling new features.
|
||||
-- An automatic downgrade to INT is intentionally prohibited.
|
||||
SELECT 'Keep BIGINT balances; use the compatible rollback binary' AS rollback_policy;
|
||||
|
||||
Reference in New Issue
Block a user