Files
myrzx_bot/tools/battle_runtime/inputs.py
T

391 lines
26 KiB
Python

"""Validate original scene/snapshot provenance and dependencies, without combat math."""
from __future__ import annotations
from collections.abc import Mapping
from contextlib import contextmanager
from contextvars import ContextVar
from functools import lru_cache
import hashlib
import json
import math
from pathlib import Path
import time
import zipfile
import zlib
from ranch_assistant.amf import Reader
from tools.battle_runtime.prepare import APK_SHA256, MAIN_SHA256, ROOT
from tools.battle_runtime.trusted import TABLE_FILES
MON_FIELDS = frozenset("id typeId level exp tpLevel tpExp feel process mode gAtk gDef gHp gDex lock sysLock nicName timeGet timeStart roomId inExploreTeam equip1 equip2 equip3 equip4 equip5 pAtk pDef pHp pDex potentialLevel giftTime skin entangle entangleLevel".split())
GLOBAL_FIELDS = frozenset(("globalAtk","globalDef","globalHp","globalDex"))
ADD_FIELDS = frozenset("atk def hp dex crit atkSpd atkVim selfCure deadBoom atkStun defStun atkPoi atkPoiDmg apCostSave skillCooldown sunFire moonHeal thorns".split())
CONTROLLERS = frozenset(("base","none","monMaker","monBuff","buff"))
MON_CONTROLLERS = frozenset("none add monMaker showFace monSteps hp skill hunluanBoom deadBoom hpArea buffMovie buffMon buff statusMov fixHurt lockTarget".split())
TRIGGERS = frozenset(("event","useSkill","time","monDead","waveStart"))
EFFECTS = frozenset("none monSkill buff monBuff buffMov event monJoin unlockWave shake showFace startController stopController".split())
# BattleAreaType advertises block in its editor dictionary, but its native
# factory returns null. Do not advertise that scene as executable.
AREAS = frozenset(("none","hp","movespd","pow","speed","powdef"))
KNOWN_ORIGINAL_IMAGE_FALLBACKS = frozenset(("data/img/monster/q/1001010_q_2s.png",))
_INSPECTION_BUDGET = ContextVar("original_runtime_inspection_budget",default=None)
class InspectionInterrupted(RuntimeError):
def __init__(self,status):
super().__init__(status)
self.status=status
def _check_budget():
budget=_INSPECTION_BUDGET.get()
if budget is not None:
cancel_event,deadline=budget
if cancel_event is not None and cancel_event.is_set(): raise InspectionInterrupted("cancelled")
if deadline is not None and time.monotonic() >= deadline: raise InspectionInterrupted("timeout")
@contextmanager
def inspection_budget(cancel_event=None,deadline=None):
"""Make the large source hash cancellable without a background thread."""
token=_INSPECTION_BUDGET.set((cancel_event,deadline))
try:
_check_budget()
yield
finally:
_INSPECTION_BUDGET.reset(token)
def _source_key():
candidates = list(ROOT.glob("*_1.9.68.apk"))
if len(candidates) != 1:
raise ValueError("Expected exactly one original *_1.9.68.apk")
path = candidates[0]
stat = path.stat()
return str(path.resolve()), stat.st_size, stat.st_mtime_ns
@lru_cache(maxsize=2)
def _load_source(path: str, size: int, modified: int):
with Path(path).open("rb") as stream:
hasher=hashlib.sha256()
while True:
_check_budget()
chunk=stream.read(4*1024*1024)
if not chunk: break
hasher.update(chunk)
if hasher.hexdigest() != APK_SHA256:
raise ValueError("Original APK SHA-256 mismatch")
tables = {}
with zipfile.ZipFile(path) as archive:
if hashlib.sha256(archive.read("assets/MYRMain.app")).hexdigest() != MAIN_SHA256:
raise ValueError("Original main SWF SHA-256 mismatch")
for name, expected in TABLE_FILES.items():
_check_budget()
member = "assets/codes/" + hashlib.md5(f"data/table/{name}.json".encode()).hexdigest()
compressed = archive.read(member)
if hashlib.sha256(compressed).hexdigest() != expected:
raise ValueError("Original table identity mismatch: " + name)
raw = zlib.decompress(compressed)
reader = Reader(raw); value = reader.read()
if reader.pos != len(raw):
raise ValueError("Trailing original AMF table bytes")
if name == "skin_info": value = value["skins"]
elif name not in ("setting","game_setting","monster_setting","team_info","potential_info","entangle_info","upstar_info"):
value = value["datas"]
if name == "stage_info" and isinstance(value,list): value = {str(row["id"]):row for row in value}
tables[name] = value
members = frozenset(archive.namelist())
return tables, members
def original_source():
_check_budget()
return _load_source(*_source_key())
def _number(value):
if isinstance(value,bool) or not isinstance(value,(str,int,float)):
return None
try:
result = float(value)
return result if math.isfinite(result) else None
except ValueError:
return None
def _list(value):
return value if isinstance(value,list) else None
def _id(value):
number = _number(value)
return str(int(number)) if number is not None and number == int(number) else ""
def _positive_id(value):
key = _id(value)
return bool(key) and 0 < int(key) <= 9007199254740991
def validate(request: Mapping, *, source=None) -> dict:
"""Return a native data-only request or precise refusal reasons.
Tables are read from the independently hashed APK, never an imported support
manifest. Supplied battle objects must equal their original context's config.
SnapshotBridge performs the original native construction and checks again.
"""
reasons, gaps, required, unit_types, skill_ids = [], [], set(), set(), set()
def refuse(code, detail): reasons.append({"code":code,"detail":detail})
try:
tables, members = original_source() if source is None else source
except (OSError,ValueError,KeyError,zipfile.BadZipFile) as error:
return {"reasons":[{"code":"original_source_unavailable","detail":str(error)}]}
context = request.get("context")
data = request.get("original_data")
roster = request.get("roster")
supplied_position = request.get("battle_position")
if supplied_position is not None and (not isinstance(supplied_position,Mapping) or set(supplied_position)-{"battleType","stageId","stageLevel","taskTypeId","taskStep"}):
return {"reasons":[{"code":"invalid_battle_position","detail":"Expected the original five-field battle position"}]}
if not isinstance(data,Mapping) or set(data)-{"source","resource_identity","battle"}:
return {"reasons":[{"code":"external_battle_data_unvalidated","detail":"Expected original_data.battle and original resource identity only"}]}
if data.get("source","original_apk") != "original_apk": refuse("resource_identity_mismatch","Expected original_apk source")
identity = data.get("resource_identity",{"apk_sha256":APK_SHA256,"main_swf_sha256":MAIN_SHA256})
if identity != {"apk_sha256":APK_SHA256,"main_swf_sha256":MAIN_SHA256}:
refuse("resource_identity_mismatch","Expected pinned original APK/main SWF")
battle = None
position = {"battleType":"stage","stageId":request.get("stage_id"),"stageLevel":str(request.get("difficulty")),"taskTypeId":None,"taskStep":0}
stage_id, difficulty = request.get("stage_id"), request.get("difficulty")
try:
if context == "ordinary_stage":
if not isinstance(stage_id,str) or type(difficulty) is not int or difficulty < 1: raise ValueError("Stage ID and integer difficulty required")
battle = tables["stage_info"][stage_id]["level"][str(difficulty)]["battle"]
if request.get("task_id") is not None or request.get("step_index") is not None: raise ValueError("Ordinary stage cannot carry task position")
elif context in ("task_battle","task_pass_stage"):
# Canonical orchestration carries the account task-instance ID in
# task_id. Its original task TYPE is explicitly in BattlePosition.
task_id = supplied_position.get("taskTypeId") if supplied_position is not None else request.get("task_id")
step_index = request.get("step_index")
if supplied_position is not None:
if step_index is not None and step_index != supplied_position.get("taskStep"):
raise ValueError("Task step selector conflicts with BattlePosition")
step_index = supplied_position.get("taskStep")
if not isinstance(task_id,str) or type(step_index) is not int or step_index < 0: raise ValueError("Task type ID and zero-based step_index required")
step = tables["task_info"][task_id]["steps"][step_index]
expected_status = "battle" if context == "task_battle" else "passStage"
if step["statusType"] != expected_status: raise ValueError("Task step statusType does not match context")
position = {"battleType":"task","stageId":None,"stageLevel":None,"taskTypeId":task_id,"taskStep":step_index}
if context == "task_battle":
if stage_id is not None: raise ValueError("Embedded task battle cannot carry an ordinary stage selector")
battle = step["battle"]
else:
stage_id, difficulty = str(step["statusValue"]["stage"]), int(step["statusValue"]["level"])
battle = tables["stage_info"][stage_id]["level"][str(difficulty)]["battle"]
if request.get("stage_id") is not None and request["stage_id"] != stage_id: raise ValueError("passStage stage selector mismatch")
else: raise ValueError("Unknown battle context")
if not isinstance(battle,dict) or not battle: raise ValueError("Original context has no battle")
except (KeyError,IndexError,TypeError,ValueError) as error:
return {"reasons":reasons+[{"code":"invalid_battle_context","detail":str(error)}]}
if "battle" not in data or data["battle"] != battle:
refuse("battle_config_mismatch","Supplied battle must equal the original config selected by its stage/task context")
if supplied_position is not None and dict(supplied_position) != position:
refuse("battle_position_mismatch","Supplied BattlePosition does not match the original selected context")
if not isinstance(roster,Mapping):
return {"reasons":reasons+[{"code":"roster_not_validated","detail":"Expected a raw original snapshot or roster.snapshot wrapper"}]}
team_name = request.get("team")
if "snapshot" in roster:
if set(roster)-{"snapshot","team_name","team_id"}:
refuse("invalid_roster","Unknown snapshot-wrapper fields")
wrapper_team = roster.get("team_name",roster.get("team_id"))
if "team_id" in roster and "team_name" in roster and roster["team_id"] != roster["team_name"]:
refuse("invalid_roster","Conflicting wrapper team selectors")
if team_name is not None and wrapper_team is not None and team_name != wrapper_team:
refuse("invalid_roster","Top-level and wrapper team selectors conflict")
if team_name is None: team_name = wrapper_team
snapshot = roster.get("snapshot")
else:
snapshot = roster
if isinstance(snapshot,Mapping) and set(snapshot)=={"time","body"}: snapshot = snapshot["body"]
if not isinstance(snapshot,Mapping) or not isinstance(team_name,str) or not team_name:
return {"reasons":reasons+[{"code":"invalid_roster","detail":"Snapshot and team_name required"}]}
for name in ("master","history","monsters","monsterAttributes","items","teams"):
if name not in snapshot: refuse("incomplete_snapshot","Missing " + name)
if reasons: return {"reasons":reasons}
master, history = snapshot["master"], snapshot["history"]
if not isinstance(master,Mapping) or not GLOBAL_FIELDS.issubset(master) or any(_number(master.get(k)) is None for k in GLOBAL_FIELDS|{"level","id"}):
refuse("incomplete_global_attributes","Original master level/id and all four global attributes are required")
elif not _positive_id(master["id"]) or not _positive_id(master["level"]):
refuse("invalid_master","Original master ID and level must be positive integers")
if not isinstance(history,Mapping) or not isinstance(history.get("monLib"),list) or not isinstance(history.get("guide_record"),(list,dict)) or "guide_main" not in history:
refuse("incomplete_battle_history","Original monLib, guide_main and guide_record required")
if isinstance(history,Mapping):
for name in ("monLib","equipLib","passAchi","guide_record","unlockCity"):
if not isinstance(history.get(name),list): refuse("incomplete_battle_history","Original history array required: "+name)
for name in ("numFeedMonsters","numKillMonsters","historyGacha","passTask","unlockTask","loopTask","unlockStage","passStage","payTypeCount","everyDayBuyProductNum"):
if not isinstance(history.get(name),dict): refuse("incomplete_battle_history","Original history object required: "+name)
for name in ("numAddMoney","numChicken","countBattle"):
if _number(history.get(name)) is None: refuse("incomplete_battle_history","Original history number required: "+name)
for name in ("unlockStage","passStage"):
if isinstance(history.get(name),dict) and any(not isinstance(value,list) for key,value in history[name].items() if key):
refuse("incomplete_battle_history","Original stage history arrays required: "+name)
for name in ("monsters","monsterAttributes","items","teams"):
if not isinstance(snapshot[name],list): refuse("invalid_snapshot_array",name)
if reasons: return {"reasons":reasons}
monsters, items = {}, {}
for row in snapshot["monsters"]:
if not isinstance(row,dict) or not MON_FIELDS.issubset(row):
refuse("incomplete_monster_snapshot","Original MonsterCenter fields are missing"); continue
key = _id(row["id"])
if not _positive_id(row["id"]) or key in monsters: refuse("invalid_monster_id","Missing or duplicate monster instance"); continue
if any(_number(row[field]) is None for field in MON_FIELDS-{"nicName","entangle","lock","sysLock","inExploreTeam","timeStart","giftTime","roomId"}): refuse("invalid_monster_fields","Original numeric monster fields required")
monsters[key] = row
if _id(row["typeId"]) not in tables["monster_info"]: refuse("unknown_monster_type","Snapshot requires a different resource version")
for row in snapshot["items"]:
if not isinstance(row,dict) or not {"id","typeId","num"}.issubset(row): refuse("incomplete_item_snapshot","Original item id/typeId/num required"); continue
key = _id(row["id"])
if not _positive_id(row["id"]) or key in items: refuse("invalid_item_id","Missing or duplicate item instance"); continue
items[key] = row
attribute_ids = set()
for row in snapshot["monsterAttributes"]:
if not isinstance(row,dict) or "monsterId" not in row or set(row)-ADD_FIELDS-{"monsterId","id","masterId"}:
refuse("unknown_monster_additions","Unsupported independent monster attribute fields")
continue
key = _id(row["monsterId"])
if key in attribute_ids or key not in monsters: refuse("invalid_monster_additions","Duplicate or orphan original attribute row")
attribute_ids.add(key)
if not ADD_FIELDS.issubset(row) or any(_number(row.get(field)) is None for field in ADD_FIELDS):
refuse("incomplete_monster_additions","Supplied original attribute rows must be complete")
teams = [row for row in snapshot["teams"] if isinstance(row,dict) and row.get("teamName")==team_name]
if len(teams)!=1 or not isinstance(teams[0].get("monsters"),list):
return {"reasons":reasons+[{"code":"invalid_selected_team","detail":"Exactly one original team with monster slots is required"}]}
selected, equipment_types = [], set()
selected_seen = set()
slots = tables["team_info"].get(teams[0].get("teamType"))
if not isinstance(slots,dict):
return {"reasons":reasons+[{"code":"unknown_team_type","detail":"Selected formation requires an original team table"}]}
for position_index,value in enumerate(teams[0]["monsters"]):
if _number(value)==0: continue
if not _positive_id(value): refuse("invalid_team_member","Expected zero or a positive original instance ID"); continue
if str(position_index) not in slots: refuse("unknown_team_slot","Occupied selected slot is absent from the original formation")
if _id(value) in selected_seen: refuse("duplicate_selected_monster","A monster cannot occupy multiple selected slots")
selected_seen.add(_id(value))
mon = monsters.get(_id(value))
if mon is None: refuse("missing_selected_monster","Selected team instance is absent from snapshot"); continue
selected.append(mon)
if _number(mon["process"]) != 3 or _number(mon["mode"]) not in (1,2): refuse("monster_unavailable","Selected monster must be out of incubation")
if not _positive_id(mon["level"]) or not _positive_id(mon["potentialLevel"]): refuse("invalid_combat_level","Selected original level and potentialLevel must be positive integers")
if _number(mon["level"]) > _number(mon["potentialLevel"]) * float(tables["potential_info"]["potentialLevelMaxAdd"]):
refuse("+50overlv","Selected level exceeds original GameMath.getMonMaxLevel(potentialLevel)")
# BattlePanel.cheatCheck uses literal 200 (not GameMath.maxFeel, whose
# optional table setting is absent from this APK).
if _number(mon["feel"]) > 200:
refuse("+15overfeel","Selected feel exceeds original BattlePanel's 200 check")
if request.get("purpose","settlement")=="settlement" and int(_id(mon["id"])) <= 100000:
refuse("player_check_exemption","Selected instance ID would bypass original player integrity checks")
if mon["inExploreTeam"] not in (0,False,"0"): refuse("monster_unavailable","Selected original monster is exploring")
for field in ("equip1","equip2","equip3","equip4","equip5"):
if _number(mon[field]) != 0:
item = items.get(_id(mon[field]))
if item is None: refuse("missing_equipment","Selected equipment instance is absent"); continue
if _id(item["typeId"]) not in tables["item_info"]: refuse("unknown_item_type","Selected equipment requires a different original item table"); continue
equipment_types.add(_id(item["typeId"]))
if item.get("itemClass") != 3 or "isUsed" not in item or not isinstance(item.get("equipParams"),str): refuse("incomplete_equipment","Original equipParams/itemClass/isUsed required"); continue
try:
parameters = json.loads(item["equipParams"])
if not ADD_FIELDS.issubset(parameters) or any(_number(parameters[k]) is None for k in ADD_FIELDS): raise ValueError()
if _number(parameters["atkPoi"]) > 0 and _number(parameters.get("atkPoiType")) is None: raise ValueError()
except (ValueError,TypeError): refuse("incomplete_equipment","Incomplete original equipment parameters")
if not selected: refuse("empty_selected_team","Original selected team contains no available monsters")
def image(path, *, native_empty_frame=False):
required.add(path)
member = "assets/codes/"+hashlib.md5(path.encode()).hexdigest()
if member not in members:
if path in KNOWN_ORIGINAL_IMAGE_FALLBACKS or native_empty_frame: gaps.append(path)
else: refuse("original_asset_missing",path)
for equip_type in equipment_types:
item_row = tables["item_info"][equip_type]
item_position = item_row.get("position")
if not isinstance(item_position,dict) or "position" not in item_position:
refuse("unknown_equipment_appearance","Original equipment position is missing")
elif str(item_position["position"]) != "0":
ornament = "_o" if item_position.get("img") else ""
image(f"data/img/item/item_{equip_type}{ornament}.png")
def unit(type_id, mode, skills=None, appearance=None):
key = _id(type_id); row = tables["monster_info"].get(key)
if row is None: refuse("unknown_monster_type",str(type_id)); return
unit_types.add(key)
image_key = _id(appearance) if appearance is not None else key
visual = tables["monster_info"].get(image_key)
if visual is None: refuse("unknown_monster_appearance",str(appearance)); return
for tag in ("","m","a","ab","s"):
fix = visual.get("imgFix",{}).get(str(int(float(mode)))+tag)
if fix is not None and not (isinstance(fix,dict) and fix.get("close") is True):
image(f"data/img/monster/q/{image_key}_q_{int(float(mode))}{tag}.png",native_empty_frame=bool(tag) and fix in ({},[]))
for skill in skills if skills is not None else [row.get("skill_1",0),row.get("skill_2",0)]:
if _number(skill) is not None and int(float(skill)) > 0:
skill_ids.add(int(float(skill)))
if _id(skill) not in tables["monster_skill"]: refuse("unknown_skill",str(skill))
for mon in selected:
appearance = mon["typeId"]
if _number(mon.get("skin",0)):
skin = tables["skin_info"].get(_id(mon["skin"]))
if skin is None: refuse("unknown_skin","Skin is not present in the pinned original resources")
elif _id(skin.get("monType")) != _id(mon["typeId"]): refuse("invalid_skin","Original skin belongs to another monster species")
else: appearance = mon["skin"]
base = tables["monster_info"].get(_id(mon["typeId"]),{})
skills = [base.get("skill_1",0),base.get("skill_2",0)]
if _number(mon.get("upStar",0)):
upstar = tables["upstar_info"].get(_id(mon["typeId"]))
if not isinstance(upstar,dict): refuse("unknown_upstar","Missing original up-star table")
else: skills = [upstar.get("skill",{}).get(str(i+1),skill) for i,skill in enumerate(skills)]
unit(mon["typeId"],mon["mode"],skills,appearance)
def rows(owner,field):
value = _list(owner.get(field,[]))
if value is None: refuse("invalid_battle_array",field); return []
return value
for team in rows(battle,"teams"):
if not isinstance(team,dict): refuse("invalid_battle_team","Original team object required"); continue
for mon in rows(team,"mons"):
if not isinstance(mon,dict) or "type" not in mon or _number(mon.get("mode")) is None:
refuse("invalid_battle_unit","Original enemy type/mode required"); continue
row = tables["monster_info"].get(_id(mon["type"]),{})
skills = [row.get("skill_1",0) if _number(mon.get("skill_1",-1))==-1 else mon["skill_1"],row.get("skill_2",0) if _number(mon.get("skill_2",-1))==-1 else mon["skill_2"]]
unit(mon["type"],mon["mode"],skills)
for controller in rows(mon,"controller"):
if controller.get("type") not in MON_CONTROLLERS: refuse("unknown_mon_controller",str(controller.get("type")))
for controller in rows(battle,"controller"):
if controller.get("type") not in CONTROLLERS: refuse("unknown_battle_controller",str(controller.get("type")))
if controller.get("type")=="monMaker":
para=controller.get("para",{});unit(para.get("monType"),para.get("mode",2))
for trigger in rows(battle,"triggers"):
if trigger.get("type") not in TRIGGERS: refuse("unknown_trigger",str(trigger.get("type")))
for effect in rows(trigger,"effects"):
if effect.get("type") not in EFFECTS: refuse("unsupported_trigger_effect",str(effect.get("type")))
field=battle.get("battleField",{})
if field.get("fieldMode"):
field = tables["setting"]["defaultField"].get(field.get("fieldName"),{}) | {"mapObjects":field.get("mapObjects",[])}
for area in rows(field,"mapAreas"):
if area.get("type","none") not in AREAS: refuse("unknown_battle_area",str(area.get("type")))
for obj in rows(field,"mapObjects"):
ground=tables["setting"]["groundObject"].get(obj.get("type"))
if ground is None: refuse("unknown_ground_object",str(obj.get("type")))
elif ground.get("img"): image(str(ground["img"]))
ground = tables["setting"]["groundType"].get(str(battle.get("groundType","1")))
if ground is None: refuse("unknown_ground_type",str(battle.get("groundType")))
else: image("data/img/bg/"+ground["battleImg"])
selected_ids = {_id(mon["id"]) for mon in selected}
equipment_ids = {_id(mon[field]) for mon in selected for field in ("equip1","equip2","equip3","equip4","equip5") if _number(mon[field]) != 0}
projection = dict(snapshot)
projection["monsters"] = selected
projection["items"] = [item for key,item in items.items() if key in equipment_ids]
projection["monsterAttributes"] = [row for row in snapshot["monsterAttributes"] if _id(row["monsterId"]) in selected_ids]
projection["teams"] = teams
native = {"scene":True,"context":context,"stage_id":stage_id,"difficulty":difficulty,
"position":position,"original_data":{"battle":battle},
"roster":{"snapshot":projection,"team_name":team_name},"allowed_missing_assets":sorted(set(gaps))}
return {"reasons":reasons,"native_request":native,"position":position,
"expected_battle_mon_ids":[] if battle.get("hideTeamMon") else [int(_id(value)) for value in teams[0]["monsters"] if _number(value) != 0],
"battle_seconds":float(battle["time"]) if float(battle.get("time",-1)) >= 0 else float(tables["game_setting"]["normalBattleTime"]),
"coverage":{"unit_type_count":len(unit_types),"skill_ids":sorted(skill_ids),"required_image_count":len(required),
"original_image_fallbacks":sorted(set(gaps)),"full_original_swf":True}}