Add v1.2 development quest progression and experimental battle runtime
This commit is contained in:
@@ -0,0 +1,421 @@
|
||||
package {
|
||||
import flash.desktop.NativeApplication;
|
||||
import flash.display.Loader;
|
||||
import flash.display.Sprite;
|
||||
import flash.events.Event;
|
||||
import flash.events.IOErrorEvent;
|
||||
import flash.events.InvokeEvent;
|
||||
import flash.events.SecurityErrorEvent;
|
||||
import flash.events.UncaughtErrorEvent;
|
||||
import flash.events.TimerEvent;
|
||||
import flash.filesystem.File;
|
||||
import flash.filesystem.FileMode;
|
||||
import flash.filesystem.FileStream;
|
||||
import flash.system.ApplicationDomain;
|
||||
import flash.system.LoaderContext;
|
||||
import flash.system.System;
|
||||
import flash.utils.ByteArray;
|
||||
import flash.utils.describeType;
|
||||
import flash.utils.getTimer;
|
||||
import flash.utils.setTimeout;
|
||||
import flash.utils.Timer;
|
||||
import flash.utils.Endian;
|
||||
|
||||
/** No game startup, login, update, networking or settlement callbacks. */
|
||||
public class OriginalProbe extends Sprite {
|
||||
private var domain:ApplicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
|
||||
private var libraries:Array = ["framework", "main", "baseui", "mainui", "mainui2", "mainui3", "movieclip"];
|
||||
private var loaders:Array = [];
|
||||
private var tables:Object;
|
||||
private var request:Object;
|
||||
private var events:Array = [];
|
||||
private var output:File;
|
||||
private var root:File;
|
||||
private var index:int = 0;
|
||||
private var finished:Boolean = false;
|
||||
private var phase:String = "invoke";
|
||||
private var sceneStarted:Boolean = false;
|
||||
private var sceneResult:Object = null;
|
||||
private var observedFrames:int = 0;
|
||||
private var sceneStartMs:int = 0;
|
||||
private var originalFrameRate:Number;
|
||||
private var engineFrameCallbacks:int = 0;
|
||||
private var assetIndex:Object;
|
||||
private var archiveStream:FileStream;
|
||||
private var crcTable:Array;
|
||||
|
||||
public function OriginalProbe() {
|
||||
System.output("ORIGINAL_PROBE_CONSTRUCTOR\n");
|
||||
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaught);
|
||||
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, invoke);
|
||||
}
|
||||
private function invoke(e:InvokeEvent):void {
|
||||
System.output("ORIGINAL_PROBE_INVOKE " + e.arguments.length + "\n");
|
||||
if (output != null) return;
|
||||
try {
|
||||
if (e.arguments.length != 3) throw new Error("Expected original-directory request-json output-json");
|
||||
root = new File(e.arguments[0]);
|
||||
output = new File(e.arguments[2]);
|
||||
request = JSON.parse(readText(new File(e.arguments[1])));
|
||||
assetIndex = JSON.parse(readText(root.resolvePath("asset_index.json")));
|
||||
if (assetIndex.apk_sha256 != "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d")
|
||||
throw new Error("Original asset archive identity mismatch");
|
||||
archiveStream = new FileStream(); archiveStream.open(new File(assetIndex.apk_path),FileMode.READ);
|
||||
tables = {};
|
||||
var tableNames:Array = JSON.parse(readText(root.resolvePath("table_index.json"))) as Array;
|
||||
for each (var tableName:String in tableNames) {
|
||||
var bytes:ByteArray = readBytes(root.resolvePath("tables/" + tableName + ".amf.zlib"));
|
||||
bytes.uncompress(); bytes.objectEncoding = 3;
|
||||
tables[tableName] = bytes.readObject();
|
||||
if (bytes.bytesAvailable != 0) throw new Error("Trailing AMF bytes: " + tableName);
|
||||
}
|
||||
var mainBytes:ByteArray = readBytes(root.resolvePath("main.library.swf"));
|
||||
var rectangleBits:uint = uint(mainBytes[8]) >> 3;
|
||||
mainBytes.position = 8 + Math.ceil((5 + 4 * rectangleBits) / 8);
|
||||
mainBytes.endian = Endian.LITTLE_ENDIAN;
|
||||
originalFrameRate = mainBytes.readUnsignedShort() / 256;
|
||||
if (originalFrameRate != 50) throw new Error("Pinned original main SWF frame rate mismatch");
|
||||
stage.frameRate = originalFrameRate;
|
||||
var watchdog:Number = request.watchdog_ms == null ? 690000 : Number(request.watchdog_ms);
|
||||
if (!isFinite(watchdog) || watchdog <= 0) throw new Error("Invalid technical watchdog");
|
||||
setTimeout(function():void { fail(new Error("Technical watchdog exceeded")); },watchdog);
|
||||
loadNext();
|
||||
} catch (error:Error) { fail(error); }
|
||||
}
|
||||
private function readText(file:File):String {
|
||||
var stream:FileStream = new FileStream(); stream.open(file, FileMode.READ);
|
||||
var result:String = stream.readUTFBytes(stream.bytesAvailable); stream.close(); return result;
|
||||
}
|
||||
private function readBytes(file:File):ByteArray {
|
||||
var stream:FileStream = new FileStream(); stream.open(file, FileMode.READ);
|
||||
var result:ByteArray = new ByteArray(); stream.readBytes(result); stream.close(); return result;
|
||||
}
|
||||
private function record(kind:String, data:Object = null):void {
|
||||
var event:Object = {kind:kind, elapsed_ms:getTimer(), phase:phase, data:data};
|
||||
events.push(event); trace("ORIGINAL_PROBE " + JSON.stringify(event));
|
||||
}
|
||||
private function loadNext():void {
|
||||
if (index == libraries.length) { measureClock(); return; }
|
||||
phase = "load_" + libraries[index++];
|
||||
var loader:Loader = new Loader(); loaders.push(loader);
|
||||
loader.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaught);
|
||||
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void {
|
||||
record("library_loaded", {name:phase, document_class:String(describeType(loader.content).@name)});
|
||||
loadNext();
|
||||
});
|
||||
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void { fail(new Error(e.text)); });
|
||||
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(e:SecurityErrorEvent):void { fail(new Error(e.text)); });
|
||||
var context:LoaderContext = new LoaderContext(false, domain); context.allowCodeImport = true;
|
||||
loader.loadBytes(readBytes(root.resolvePath(libraries[index-1] + ".library.swf")), context);
|
||||
}
|
||||
private function cls(name:String):Class { return domain.getDefinition(name) as Class; }
|
||||
private function measureClock():void {
|
||||
phase = "measure_hidden_clock";
|
||||
stage.frameRate = originalFrameRate;
|
||||
// Let startup/loading work drain before measuring the hidden stage.
|
||||
setTimeout(measureClockWindow,300);
|
||||
}
|
||||
private function measureClockWindow():void {
|
||||
var start:int = getTimer(), frames:int = 0, ticks:int = 0;
|
||||
var timer:Timer = new Timer(100);
|
||||
var frame:Function = function(e:Event):void { frames++; };
|
||||
timer.addEventListener(TimerEvent.TIMER, function(e:TimerEvent):void { ticks++; });
|
||||
stage.addEventListener(Event.ENTER_FRAME, frame); timer.start();
|
||||
setTimeout(function():void {
|
||||
timer.stop(); stage.removeEventListener(Event.ENTER_FRAME, frame);
|
||||
var elapsed:int = getTimer() - start;
|
||||
record("clock_measured", {requested_fps:stage.frameRate, observed_frames:frames,
|
||||
elapsed_ms:elapsed, observed_fps:frames * 1000 / elapsed,
|
||||
stage_width:stage.stageWidth,stage_height:stage.stageHeight,
|
||||
timer_period_ms:100, timer_ticks:ticks, native_window_visible:stage.nativeWindow.visible});
|
||||
probe();
|
||||
}, 2500);
|
||||
}
|
||||
private function reflect(name:String):void {
|
||||
var type:XML = describeType(cls(name));
|
||||
var stream:FileStream = new FileStream();
|
||||
stream.open(output.parent.resolvePath(name.replace(/\./g,"_") + ".xml"), FileMode.WRITE);
|
||||
stream.writeUTFBytes(type.toXMLString()); stream.close();
|
||||
record("definition_resolved", {name:name});
|
||||
}
|
||||
private function probe():void {
|
||||
try {
|
||||
phase = "inject_original_tables";
|
||||
var table:Class = cls("net.pixvi.myr.center.Table");
|
||||
for (var key:String in tables) {
|
||||
if (key == "monster_fix") continue;
|
||||
var value:Object = tables[key];
|
||||
if (key != "team_info" && value != null && value.hasOwnProperty("datas")) value = value.datas;
|
||||
table[key] = value;
|
||||
}
|
||||
table["skin_info"] = tables.skin_info.skins;
|
||||
table["upstar_info"] = tables.upstar_info;
|
||||
table["city_info"] = table["game_setting"].cityInfo;
|
||||
table["entangle_skill"] = table["entangle_info"].entangleSkill;
|
||||
table["stage_info"] = cls("net.pixvi.pfw.utils.ObjectUtil")["tableToObject"](tables.stage_info.datas);
|
||||
table["monster_group"] = table["monster_setting"].group;
|
||||
table["monster_element"] = table["monster_setting"].element;
|
||||
record("tables_injected");
|
||||
phase = "initialize_synthetic_master";
|
||||
var gameClass:Class = cls("net.pixvi.myr.center.Game");
|
||||
var masterClass:Class = cls("net.pixvi.myr.element.master.MasterVo");
|
||||
var master:Object = new masterClass();
|
||||
gameClass["getIns"]()["master"] = master; master["init"]();
|
||||
master["history"]["monLib"] = [];
|
||||
record("synthetic_master_initialized", {source:"original MasterVo.init",account:false});
|
||||
phase = "original_framework_bootstrap";
|
||||
addChild(cls("net.pixvi.common.center.StartUpCenter")["startUp"](stage,true,false,false,false));
|
||||
record("original_framework_layers_initialized");
|
||||
var rm:Class = cls("net.pixvi.common.manager.resource.RM");
|
||||
rm["getInstance"]();
|
||||
record("original_resource_managers_initialized");
|
||||
var stringLoader:Class = cls("net.pixvi.pfw.net.PiStringLoader");
|
||||
var cryptor:Class = cls("net.pixvi.myrcryptor.MYRCryptor");
|
||||
stringLoader["globalCryptoMode"] = true;
|
||||
stringLoader["globalJsonCryptoModeFunction"] = cryptor["jsonDecodeHandler"];
|
||||
var resourceClass:Class = cls("net.pixvi.common.net.resource.ResourceVo");
|
||||
for (var tableKey:String in tables) {
|
||||
var resource:Object = new resourceClass("data/table/" + tableKey + ".json");
|
||||
resource["crypto"] = true;
|
||||
resource["data"] = readBytes(root.resolvePath("tables/" + tableKey + ".amf.zlib"));
|
||||
rm["TXT"]["push"](resource);
|
||||
}
|
||||
var netImg:Class = cls("net.pixvi.pfw.display.NetImg");
|
||||
netImg["globalImgCryptoMode"] = true;
|
||||
netImg["globalImgCryptoGetBytes"] = originalAssetBytes;
|
||||
netImg["globalImgSrcHack"] = localAssetPath;
|
||||
var net:Class = cls("net.pixvi.myr.net.NetCenter");
|
||||
var offlineBase:String = output.parent.resolvePath("__offline_game_api_denied__/").url + "/";
|
||||
net["SERVER"] = net["PAY_SERVER"] = net["CENTER_SERVER"] = offlineBase;
|
||||
if (request.scene === true) {
|
||||
bootstrapDisplay();
|
||||
var sceneData:Object = request.original_data != null ? request.original_data.battle :
|
||||
table["stage_info"][request.stage_id].level[String(request.difficulty)].battle;
|
||||
startScene(master,cls("net.pixvi.myr.element.mon.MonsterVo"),sceneData);
|
||||
return;
|
||||
}
|
||||
phase = "original_GameMath";
|
||||
var math:Class = cls("net.pixvi.myr.GameMath");
|
||||
var rolls:Array = [];
|
||||
for (var i:int=0; i<8; i++) rolls.push(math["damage"](100,20,20,30));
|
||||
record("GameMath_executed", {damage_rolls:rolls, ap_cd:math["apCD"], dex_attack_adjustment:math["addAtkSpdByDex"](40)});
|
||||
phase = "reflect_original_framework";
|
||||
for each (var name:String in ["net.pixvi.common.driver.StageDriver", "net.pixvi.common.driver.SecondDriver",
|
||||
"net.pixvi.common.manager.resource.RM", "net.pixvi.common.view.FF", "net.pixvi.pfw.display.BitFactory",
|
||||
"net.pixvi.myr.center.BattleCenter", "net.pixvi.myr.element.mon.MonsterVo",
|
||||
"net.pixvi.myr.element.battle.BattleMonVo", "net.pixvi.myr.element.battle.BattleVo",
|
||||
"net.pixvi.common.utils.StageLocator", "net.pixvi.common.utils.PiFixVo", "net.pixvi.pfw.driver.EnterFrameDriver"]) reflect(name);
|
||||
phase = "original_MonsterVo";
|
||||
var monsterClass:Class = cls("net.pixvi.myr.element.mon.MonsterVo");
|
||||
var monster:Object = new monsterClass(1001010);
|
||||
monster["buildByArea"](); monster["level"] = 1; monster["mode"] = 2;
|
||||
record("MonsterVo_executed", {type:monster["type"],level:monster["level"],hp:monster["hp"],atk:monster["atk"],dex:monster["dex"]});
|
||||
phase = "original_BattleMonVo";
|
||||
var monClass:Class = cls("net.pixvi.myr.element.battle.BattleMonVo");
|
||||
var mon:Object = new monClass(); mon["buildByMonster"](monster);
|
||||
record("BattleMonVo_executed", {hp:mon["hp"],atk:mon["atk"],spd_atk:mon["spd_atk"],spd_mov:mon["spd_mov"],skill_1:mon["skill_1"]});
|
||||
phase = "original_BattleVo";
|
||||
var battleClass:Class = cls("net.pixvi.myr.element.battle.BattleVo");
|
||||
var battle:Object = new battleClass();
|
||||
var stages:Object = table["stage_info"];
|
||||
if (stages is Array) {
|
||||
var mapped:Object = {};
|
||||
for each (var row:Object in stages) mapped[row.id] = row;
|
||||
stages = mapped;
|
||||
}
|
||||
var battleData:Object = stages[request.stage_id].level[String(request.difficulty)].battle;
|
||||
battle["buildByObject"](battleData);
|
||||
record("BattleVo_executed", {time:battle["time"],teams:battle["teams"].length,enemy_count:battle["teams"][0].mons.length});
|
||||
bootstrapDisplay();
|
||||
phase = "original_BattleGround_constructor";
|
||||
reflect("net.pixvi.myr.battle.BattleGround");
|
||||
var groundClass:Class = cls("net.pixvi.myr.battle.BattleGround");
|
||||
groundClass["firstStartUp"]();
|
||||
var ground:Object = new groundClass();
|
||||
record("BattleGround_constructed");
|
||||
finish("probe_completed", null);
|
||||
} catch (error:Error) { fail(error); }
|
||||
}
|
||||
private function bootstrapDisplay():void {
|
||||
phase = "original_display_bootstrap";
|
||||
var fixClass:Class = cls("net.pixvi.common.utils.PiFixVo");
|
||||
var fs1:Object = new fixClass(); fs1["id"] = "fs1"; fs1["maxHWScale"] = 1.775;
|
||||
var fs2:Object = new fixClass(); fs2["id"] = "fs2"; fs2["maxHWScale"] = 1.9125;
|
||||
cls("net.pixvi.common.utils.StageLocator")["autoFull"](720,1136,[fs1,fs2]);
|
||||
// The ORIGINAL constructor calls startup(). Calling it again
|
||||
// creates another ENTER_FRAME source and corrupts delta timing.
|
||||
cls("net.pixvi.pfw.driver.EnterFrameDriver")["getInstance"]()["regist"](countEngineFrame);
|
||||
cls("net.pixvi.common.driver.SecondDriver")["getInstance"]()["startup"]();
|
||||
}
|
||||
private function startScene(master:Object, monsterClass:Class, battleData:Object):void {
|
||||
phase = "original_BattleCenter_startBattle";
|
||||
if (request.roster != null && request.roster.snapshot != null) {
|
||||
phase = "original_snapshot_bridge";
|
||||
var bridge:Class = ApplicationDomain.currentDomain.getDefinition("SnapshotBridge") as Class;
|
||||
var built:Object = bridge["build"](domain,request.roster.snapshot,request.roster.team_name);
|
||||
master = built.master;
|
||||
cls("net.pixvi.myr.center.Game")["getIns"]()["master"] = master;
|
||||
master["curBattleTeam"] = request.roster.team_name;
|
||||
record("snapshot_bridge_built",built.metadata == null ? built.validation : built.metadata);
|
||||
} else {
|
||||
var teamClass:Class = cls("net.pixvi.myr.element.team.TeamVo");
|
||||
var team:Object = new teamClass(); team["monsters"] = [1000001,1000002,1000003,0,0,0,0,0];
|
||||
master["teams"] = [team]; master["name"] = "offline synthetic fixture";
|
||||
for (var i:int = 1; i <= 3; i++) {
|
||||
var mon:Object = new monsterClass(1001010);
|
||||
mon["buildByArea"](); mon["level"] = 1; mon["mode"] = 2; mon["id"] = 1000000+i;
|
||||
master["monsters"].push(mon);
|
||||
}
|
||||
}
|
||||
phase = "original_BattleCenter_startBattle";
|
||||
var sound:Class = cls("net.pixvi.common.center.SoundCenter");
|
||||
sound["getIns"]()["setBgmEnable"](false); sound["getIns"]()["setEffectEnable"](false);
|
||||
var positionClass:Class = cls("net.pixvi.myr.element.battle.BattlePosition");
|
||||
var position:Object = new positionClass();
|
||||
if (request.position != null) {
|
||||
cls("net.pixvi.pfw.utils.Mapper")["fillVariables"](position,request.position);
|
||||
} else {
|
||||
position["battleType"] = "stage"; position["stageId"] = request.stage_id; position["stageLevel"] = String(request.difficulty);
|
||||
}
|
||||
var panelClass:Class = cls("net.pixvi.myr.panel.battle.BattlePanel");
|
||||
var panel:Object = panelClass["getIns"]();
|
||||
panel["onWinCallBack"] = sceneComplete; panel["onLoseCallBack"] = sceneComplete;
|
||||
cls("net.pixvi.myr.center.BattleCenter")["getIns"]()["startBattle"](position,battleData,{},null,null);
|
||||
record("BattleCenter_started", {context:request.context,master_level:master["level"], ap:master["ap"],
|
||||
callbacks:"original BattlePanel checks followed by local result collection only"});
|
||||
setTimeout(function():void {
|
||||
try {
|
||||
phase = "original_battle_ready_animation";
|
||||
panel["battleStartReady"]();
|
||||
stage.addEventListener(Event.ENTER_FRAME, countSceneFrame);
|
||||
sceneStartMs = getTimer();
|
||||
observeScene();
|
||||
} catch (error:Error) { fail(error); }
|
||||
}, 700);
|
||||
}
|
||||
private function countSceneFrame(e:Event):void { observedFrames++; }
|
||||
private function countEngineFrame():void { engineFrameCallbacks++; }
|
||||
private function observeScene():void {
|
||||
if (finished) return;
|
||||
try {
|
||||
var panelClass:Class = cls("net.pixvi.myr.panel.battle.BattlePanel");
|
||||
var panel:Object = panelClass["getIns"]();
|
||||
var ground:Object = panel["ground"];
|
||||
sceneStarted = sceneStarted || ground["battleIsStart"];
|
||||
phase = sceneStarted ? "original_battle_frames" : "original_battle_ready_animation";
|
||||
var units:Array = [];
|
||||
for each (var mon:Object in ground["monsters"]) {
|
||||
units.push({id:mon["monVo"]["mid"],team:mon["team"],x:mon["x"],y:mon["y"],
|
||||
hp:mon["monVo"]["hp"],skill_1:mon["monVo"]["skill_1"],skill_2:mon["monVo"]["skill_2"]});
|
||||
}
|
||||
record("scene_sample", {started:ground["battleIsStart"], paused:ground["paused"],
|
||||
requested_fps:stage.frameRate,
|
||||
engine_frame_callbacks:engineFrameCallbacks,
|
||||
engine_frame_delta_ms:cls("net.pixvi.pfw.driver.EnterFrameDriver")["frameSpaceTime"],
|
||||
left_ms:ground["battleTime"]["leftTime"],ap:ground["vo"]["teamDic"][1]["ap"],
|
||||
units:units, observed_frames:observedFrames, wall_ms:getTimer()-sceneStartMs});
|
||||
if (!sceneStarted) panel["startMovTouchHandler"]();
|
||||
setTimeout(observeScene, 1000);
|
||||
} catch (error:Error) { fail(error); }
|
||||
}
|
||||
private function sceneComplete(data:Object):void {
|
||||
try {
|
||||
phase = "original_BattlePanel_result_callback";
|
||||
sceneStarted = true;
|
||||
var raw:Object = data["cheatRecords"];
|
||||
if (cls("net.pixvi.myr.net.NetCenter")["getIns"]()["reqid"] != 0)
|
||||
throw new Error("Original scene attempted an unavailable offline game API");
|
||||
var unitRecords:Array = [];
|
||||
var panelClass:Class = cls("net.pixvi.myr.panel.battle.BattlePanel");
|
||||
var ground:Object = panelClass["getIns"]()["ground"];
|
||||
var objectUtil:Class = cls("net.pixvi.pfw.utils.ObjectUtil");
|
||||
for each (var team:Object in ground["vo"]["teams"]) {
|
||||
var allUnits:Array = team["mons"].concat(team["stageMons"]).concat(team["deadMons"]);
|
||||
for each (var mon:Object in allUnits) {
|
||||
unitRecords.push({team:mon["team"],mode:mon["monVo"]["mode"],
|
||||
summon:mon["monVo"]["summonUnit"],dead:mon["monVo"]["dead"],hp_left:mon["monVo"]["hp"],
|
||||
original_hurt_record:mon["getTotalHurtRecort"](),
|
||||
original_record:objectUtil["deepClone"](mon["makeRecord"]())});
|
||||
}
|
||||
}
|
||||
sceneResult = {outcome:data["win"] ? "win" : "loss",terminal_reason:data["leftTime"] == 0 ? "time_limit" : (data["win"] ? "victory_condition" : "loss_condition"), battle_data:data["getObj"](),
|
||||
anomaly_records:{mons:raw["mons"],damages:raw["damages"],master:raw["master"],text:raw["text"]},
|
||||
original_unit_records:unitRecords,
|
||||
requested_fps:stage.frameRate,observed_fps:observedFrames*1000/(getTimer()-sceneStartMs),
|
||||
engine_frame_callbacks:engineFrameCallbacks,game_api_requests:0,
|
||||
observed_frames:observedFrames, wall_ms:getTimer()-sceneStartMs};
|
||||
record("original_battle_completed", sceneResult);
|
||||
finish("scene_completed", null);
|
||||
} catch (error:Error) { fail(error); }
|
||||
}
|
||||
private function uncaught(e:UncaughtErrorEvent):void {
|
||||
e.preventDefault(); fail(e.error is Error ? e.error as Error : new Error(String(e.error)));
|
||||
}
|
||||
private function localAssetPath(path:String):String {
|
||||
if (path.indexOf(":") >= 0 || path.indexOf("..") >= 0 || path.indexOf("\\") >= 0 || path.charAt(0) == "/")
|
||||
throw new Error("Offline resource path refused: " + path);
|
||||
return path;
|
||||
}
|
||||
private function originalAssetBytes(path:String):ByteArray {
|
||||
localAssetPath(path);
|
||||
var cryptor:Class = cls("net.pixvi.myrcryptor.MYRCryptor");
|
||||
var hashed:String = cryptor["getHashSrc"](path);
|
||||
var entry:Object = assetIndex.entries[hashed.substr(6)];
|
||||
if (entry == null) {
|
||||
record("original_asset_read", {path:path, member:hashed, crc32:null});
|
||||
// Match MYRCryptor.getHashSrcBytes. NetBitImg then attempts the
|
||||
// relative local file and dispatches its ORIGINAL error/complete
|
||||
// callbacks. Do not manufacture pixels or suppress the record.
|
||||
record("original_asset_missing", {path:path, member:hashed, behavior:"original local IO-error fallback"});
|
||||
var permitted:Array = request.allowed_missing_assets == null ? ["data/img/monster/q/1001010_q_2s.png"] : request.allowed_missing_assets as Array;
|
||||
if (permitted == null || permitted.indexOf(path) < 0) throw new Error("Unknown original asset dependency: " + path);
|
||||
return null;
|
||||
}
|
||||
if (entry.size > 67108864 || entry.compressed_size > 67108864 || entry.offset < 0)
|
||||
throw new Error("Original image resource exceeds supported bounds: " + path);
|
||||
var bytes:ByteArray = new ByteArray();
|
||||
archiveStream.position = entry.offset;
|
||||
archiveStream.readBytes(bytes,0,entry.compressed_size);
|
||||
if (entry.method == 8) bytes.uncompress("deflate");
|
||||
else if (entry.method != 0) throw new Error("Unsupported original ZIP method");
|
||||
var checksum:uint = crc32(bytes);
|
||||
if (bytes.length != entry.size || checksum != uint(entry.crc32))
|
||||
throw new Error("Original asset ZIP content mismatch: " + path);
|
||||
record("original_asset_read", {path:path, member:hashed, crc32:checksum, bytes:bytes.length});
|
||||
bytes.position = 0;
|
||||
return bytes;
|
||||
}
|
||||
private function crc32(bytes:ByteArray):uint {
|
||||
if (crcTable == null) {
|
||||
crcTable = [];
|
||||
for (var n:uint=0; n<256; n++) {
|
||||
var value:uint=n;
|
||||
for (var bit:uint=0; bit<8; bit++) value=(value & 1) ? uint(0xedb88320 ^ (value >>> 1)) : value >>> 1;
|
||||
crcTable.push(value);
|
||||
}
|
||||
}
|
||||
var checksum:uint=0xffffffff;
|
||||
for (var i:uint=0; i<bytes.length; i++) checksum=uint(crcTable[(checksum ^ bytes[i]) & 255]) ^ (checksum >>> 8);
|
||||
return uint(checksum ^ 0xffffffff);
|
||||
}
|
||||
private function fail(error:Error):void {
|
||||
finish("blocked", {phase:phase, name:error.name, message:error.message, stack:error.getStackTrace()});
|
||||
}
|
||||
private function finish(status:String, error:Object):void {
|
||||
if (finished) return; finished = true;
|
||||
if (archiveStream != null) { archiveStream.close(); archiveStream = null; }
|
||||
var result:Object = {schema:1, status:status, scope:request != null && request.scene === true ? "original_scene_experiment" : "original_component_probe",
|
||||
nonce:request == null ? null : request.nonce,
|
||||
application_id:NativeApplication.nativeApplication.applicationID,
|
||||
storage_directory:File.applicationStorageDirectory.nativePath,
|
||||
battle_executed:sceneStarted, scene_result:sceneResult,
|
||||
settlement_eligible:false, events:events, error:error};
|
||||
trace("ORIGINAL_PROBE_RESULT " + JSON.stringify(result));
|
||||
if (output != null) {
|
||||
var stream:FileStream = new FileStream(); stream.open(output, FileMode.WRITE);
|
||||
stream.writeUTFBytes(JSON.stringify(result)); stream.close();
|
||||
}
|
||||
NativeApplication.nativeApplication.exit(status == "probe_completed" || status == "scene_completed" ? 0 : 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package {
|
||||
import flash.system.ApplicationDomain;
|
||||
|
||||
/**
|
||||
* Offline adapter for RAW loadMasterData snapshots, never derived stats.
|
||||
*
|
||||
* Contract: after original Table/RM initialization, call
|
||||
* var roster:Object = SnapshotBridge.build(domain, rawSnapshot, "teamA");
|
||||
* Returns {master: original MasterVo, selectedTeam: original TeamVo,
|
||||
* validation: JSON-safe provenance/selection metadata}.
|
||||
* Success installs master in this domain's Game.getIns().master because
|
||||
* original MonsterVo/BagCenter/TeamCenter getters use the Master accessor.
|
||||
* Failure throws Error("SnapshotBridge[code] path: explanation") and leaves
|
||||
* the previous Game.master installed. Input snapshots are never mutated.
|
||||
* Caller owns BattlePosition, battle contexts, resources and result handling.
|
||||
* Required raw roots: master, monsters, items, teams, monsterAttributes,
|
||||
* history. An explicit empty monsterAttributes array is valid: absent rows
|
||||
* leave the ORIGINAL MonsterAdd constructor state unchanged. Present rows
|
||||
* need explicit values for every ADD_FIELDS key; no bonuses are rebuilt.
|
||||
* Equipment requires itemClass 3 and the original JSON-string equipParams.
|
||||
*
|
||||
* Source references below are relative to analysis/as3/scripts/net/pixvi/myr/.
|
||||
* Only the pure loader calls from center/MasterCenter.as:loadMasterData are
|
||||
* used. Do not call loadMasterData itself: its surrounding startup path
|
||||
* accesses SDK, account, persistence, achievements and UI state.
|
||||
*/
|
||||
public class SnapshotBridge {
|
||||
private static const ADD_FIELDS:Array = ["atk", "def", "hp", "dex", "crit", "atkSpd",
|
||||
"atkVim", "selfCure", "deadBoom", "atkStun", "defStun", "atkPoi", "atkPoiDmg",
|
||||
"apCostSave", "skillCooldown", "sunFire", "moonHeal", "thorns"];
|
||||
private static const MON_FIELDS:Array = ["id", "typeId", "level", "exp", "tpLevel", "tpExp",
|
||||
"feel", "process", "mode", "gAtk", "gDef", "gHp", "gDex", "pAtk", "pDef", "pHp",
|
||||
"pDex", "potentialLevel", "equip1", "equip2", "equip3", "equip4", "equip5",
|
||||
"entangleLevel", "skin"];
|
||||
|
||||
public static function build(domain:ApplicationDomain, snapshot:Object, teamName:String):Object {
|
||||
if (domain == null) reject("domain", "domain", "original ApplicationDomain is required");
|
||||
objectAt(snapshot, "snapshot");
|
||||
if (teamName == null || teamName.length == 0)
|
||||
reject("team_name", "teamName", "select an explicit snapshot team");
|
||||
// Copy before calling loaders: BagCenter adds equipPara and HistoryVo
|
||||
// normalizes maps/flags in place (center/BagCenter.as:getItemByItemData;
|
||||
// element/master/HistoryVo.as:loadHistoryData).
|
||||
var data:Object = copy(snapshot);
|
||||
var rawMaster:Object = objectAt(data.master, "master");
|
||||
numbers(rawMaster, ["id", "level", "globalAtk", "globalDef", "globalHp", "globalDex"], "master");
|
||||
positiveId(rawMaster.id, "master.id", 2147483647);
|
||||
positiveId(rawMaster.level, "master.level", 2147483647);
|
||||
var monsters:Array = arrayAt(data.monsters, "monsters");
|
||||
var items:Array = arrayAt(data.items, "items");
|
||||
var teams:Array = arrayAt(data.teams, "teams");
|
||||
var attributes:Array = arrayAt(data.monsterAttributes, "monsterAttributes");
|
||||
validateHistory(data);
|
||||
|
||||
var table:Class = definition(domain, "net.pixvi.myr.center.Table");
|
||||
for each (var tableName:String in ["monster_info", "item_info", "game_setting", "team_info", "task_info"])
|
||||
objectAt(table[tableName], "Table." + tableName);
|
||||
// Table.startUp normally derives city_info from game_setting.cityInfo;
|
||||
// the caller may instead inject it. The history loader tolerates null
|
||||
// city_info; this bridge never rewrites caller resource tables.
|
||||
var monById:Object = {};
|
||||
var attrById:Object = {};
|
||||
var itemById:Object = {};
|
||||
var equipment:Object = {};
|
||||
var rawTeam:Object = null;
|
||||
var names:Object = {};
|
||||
var i:int;
|
||||
var row:Object;
|
||||
var path:String;
|
||||
var key:String;
|
||||
for (i = 0; i < monsters.length; i++) {
|
||||
path = "monsters[" + i + "]"; row = objectAt(monsters[i], path);
|
||||
numbers(row, MON_FIELDS, path);
|
||||
positiveId(row.id, path + ".id"); positiveId(row.typeId, path + ".typeId", 2147483647);
|
||||
// Non-selected eggs may legitimately carry level/potential 0.
|
||||
// Positive combat levels are required below for selected IDs.
|
||||
flag(row.inExploreTeam, path + ".inExploreTeam"); flag(row.entangle, path + ".entangle");
|
||||
if (monById.hasOwnProperty(String(row.id))) reject("duplicate_monster", path + ".id", "duplicate instance ID");
|
||||
monById[String(row.id)] = row;
|
||||
if (table["monster_info"][row.typeId] == null)
|
||||
reject("monster_type", path + ".typeId", "missing original monster table row");
|
||||
if (row.skin > 0) {
|
||||
// center/Table.as:startUp assigns RM.TXT.getJson("skin_info").skins.
|
||||
// element/mon/SkinVo.as:table indexes that FLAT map by typeId.
|
||||
var skins:Object = objectAt(table["skin_info"], "Table.skin_info");
|
||||
if (skins[row.skin] == null || Number(skins[row.skin].monType) != row.typeId)
|
||||
reject("skin", path + ".skin", "skin must exist for this monster species");
|
||||
}
|
||||
// MonsterCenter itself supplies table skills, up-star skills,
|
||||
// potential PointLockers, SkinVo and decoded entangleSkills.
|
||||
if (row.upStar != null && Number(row.upStar) > 0) {
|
||||
numbers(row, ["upStar"], path);
|
||||
if (table["upstar_info"] == null || table["upstar_info"][row.typeId] == null)
|
||||
reject("upstar", path + ".upStar", "missing original up-star table row");
|
||||
}
|
||||
if (row.entangleSkills != null) {
|
||||
var entangleSkills:Object = jsonObject(row.entangleSkills, path + ".entangleSkills");
|
||||
for (key in entangleSkills) {
|
||||
if (Number(entangleSkills[key]) > 0 && (table["entangle_info"] == null ||
|
||||
table["entangle_info"].entangleSkill == null ||
|
||||
table["entangle_info"].entangleSkill[entangleSkills[key]] == null))
|
||||
reject("entangle_skill", path + ".entangleSkills", "missing original entangle skill");
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i = 0; i < attributes.length; i++) {
|
||||
path = "monsterAttributes[" + i + "]"; row = objectAt(attributes[i], path);
|
||||
positiveId(row.monsterId, path + ".monsterId");
|
||||
key = String(row.monsterId);
|
||||
if (attrById.hasOwnProperty(key)) reject("duplicate_attributes", path + ".monsterId", "ambiguous instance attributes");
|
||||
if (!monById.hasOwnProperty(key)) reject("orphan_attributes", path + ".monsterId", "monster instance is absent");
|
||||
numbers(row, ADD_FIELDS, path);
|
||||
attrById[key] = row;
|
||||
}
|
||||
var itemVoClass:Class = definition(domain, "net.pixvi.myr.element.bag.ItemVo");
|
||||
var itemTypeClass:Class = definition(domain, "net.pixvi.myr.element.bag.ItemType");
|
||||
for (i = 0; i < items.length; i++) {
|
||||
path = "items[" + i + "]"; row = objectAt(items[i], path);
|
||||
numbers(row, ["id", "typeId", "num"], path);
|
||||
positiveId(row.id, path + ".id"); positiveId(row.typeId, path + ".typeId", 2147483647);
|
||||
if (itemById.hasOwnProperty(String(row.id))) reject("duplicate_item", path + ".id", "duplicate inventory instance ID");
|
||||
itemById[String(row.id)] = row;
|
||||
if (table["item_info"][row.typeId] == null && table["monster_info"][row.typeId] == null)
|
||||
reject("item_type", path + ".typeId", "missing original item/egg table row");
|
||||
if (itemVoClass["getItemType"](row.typeId) == itemTypeClass["TYPE_EQUIP"]) {
|
||||
numbers(row, ["itemClass", "isUsed"], path);
|
||||
if (row.itemClass != 3) reject("equipment_class", path + ".itemClass", "original equipment loader requires itemClass 3");
|
||||
// Preflight avoids BagCenter's missing-params Alert/fake-zero
|
||||
// error branch. The original loader still decodes equipParams.
|
||||
var equip:Object = jsonObject(row.equipParams, path + ".equipParams");
|
||||
numbers(equip, ADD_FIELDS, path + ".equipParams");
|
||||
if (equip.atkPoi > 0) numbers(equip, ["atkPoiType"], path + ".equipParams");
|
||||
equipment[String(row.id)] = row;
|
||||
}
|
||||
}
|
||||
for (i = 0; i < monsters.length; i++) {
|
||||
row = monsters[i];
|
||||
for (var slot:int = 1; slot <= 5; slot++) {
|
||||
var equipId:Number = Number(row["equip" + slot]);
|
||||
if (equipId < 0 || equipId > 2147483647 || equipId != Math.floor(equipId))
|
||||
reject("equipment_id", "monsters[" + i + "].equip" + slot, "expected zero or inventory instance ID within original equip:int range");
|
||||
if (equipId > 0 && !equipment.hasOwnProperty(String(equipId)))
|
||||
reject("missing_equipment", "monsters[" + i + "].equip" + slot, "equipped inventory instance is absent or is not equipment");
|
||||
}
|
||||
}
|
||||
var selectedIds:Array = [];
|
||||
var selectedSlots:Array = [];
|
||||
var selectedSeen:Object = {};
|
||||
for (i = 0; i < teams.length; i++) {
|
||||
path = "teams[" + i + "]"; row = objectAt(teams[i], path);
|
||||
if (!(row.teamName is String) || row.teamName.length == 0 || !(row.teamType is String))
|
||||
reject("team_fields", path, "original teamName and teamType are required");
|
||||
if (names.hasOwnProperty(row.teamName)) reject("duplicate_team", path + ".teamName", "ambiguous team name");
|
||||
names[row.teamName] = true;
|
||||
var rawSlots:Array = arrayAt(row.monsters, path + ".monsters");
|
||||
var slotInfo:Object = objectAt(table["team_info"][row.teamType], "Table.team_info." + row.teamType);
|
||||
for (var pos:int = 0; pos < rawSlots.length; pos++) {
|
||||
var mid:Number = numberAt(rawSlots[pos], path + ".monsters[" + pos + "]");
|
||||
if (mid < 0 || mid != Math.floor(mid)) reject("team_member_id", path + ".monsters[" + pos + "]", "expected zero or positive monster instance ID");
|
||||
// Original loaders may discard trailing empty padding. An
|
||||
// occupied unsupported position must never be discarded.
|
||||
if (slotInfo[pos] == null && mid > 0) reject("team_slot", path + ".monsters[" + pos + "]", "occupied position is absent from the original team table");
|
||||
if (mid > 0 && !monById.hasOwnProperty(String(mid)))
|
||||
reject("missing_team_member", path + ".monsters[" + pos + "]", "reference must be a supplied monster instance ID, not a species ID");
|
||||
if (row.teamName == teamName && mid > 0) {
|
||||
var member:Object = monById[String(mid)];
|
||||
if (selectedSeen.hasOwnProperty(String(mid))) reject("duplicate_member", path, "monster instance occupies multiple selected slots");
|
||||
selectedSeen[String(mid)] = true;
|
||||
if (member.process != 3 || (member.mode != 1 && member.mode != 2))
|
||||
reject("incubating_member", path + ".monsters[" + pos + "]", "selected monster must be out of incubation (process 3, mode 1 or 2)");
|
||||
if (member.inExploreTeam == true)
|
||||
reject("exploring_member", path + ".monsters[" + pos + "]", "selected monster is exploring");
|
||||
positiveId(member.level, path + ".monsters[" + pos + "].level", 2147483647);
|
||||
positiveId(member.potentialLevel, path + ".monsters[" + pos + "].potentialLevel", 2147483647);
|
||||
selectedIds.push(mid); selectedSlots.push(pos);
|
||||
}
|
||||
}
|
||||
if (row.teamName == teamName) rawTeam = row;
|
||||
}
|
||||
if (rawTeam == null) reject("team_missing", "teams", "requested teamName is absent");
|
||||
if (selectedIds.length == 0) reject("empty_team", "teams", "selected team has no positive monster instance IDs");
|
||||
|
||||
var game:Object = definition(domain, "net.pixvi.myr.center.Game")["getIns"]();
|
||||
var previous:Object = game["master"];
|
||||
var masterClass:Class = definition(domain, "net.pixvi.myr.element.master.MasterVo");
|
||||
var monsterCenter:Class = definition(domain, "net.pixvi.myr.center.MonsterCenter");
|
||||
var bagCenter:Class = definition(domain, "net.pixvi.myr.center.BagCenter");
|
||||
var teamCenter:Class = definition(domain, "net.pixvi.myr.center.TeamCenter");
|
||||
var master:Object = new masterClass();
|
||||
try {
|
||||
game["master"] = master; master["init"]();
|
||||
// center/MasterCenter.as:loadMasterData scalar mapping. AP is
|
||||
// read-only MasterVo.ap -> GameMath.apByLevel(raw level).
|
||||
for each (key in ["id", "createTime", "level", "farmName", "avatar", "exp", "money", "ti", "ke"])
|
||||
if (rawMaster.hasOwnProperty(key)) master[key] = rawMaster[key];
|
||||
if (rawMaster.hasOwnProperty("roleName")) master["name"] = rawMaster.roleName;
|
||||
if (rawMaster.hasOwnProperty("timeTi")) master["timeTi"] = rawMaster.timeTi / 1000;
|
||||
master["curBattleTeam"] = teamName;
|
||||
// Native reflection confirms HistoryVo.loadHistoryData(Object,
|
||||
// Object); there is no HistoryVo.onData API in this SWF.
|
||||
master["history"]["loadHistoryData"](data.history, data.data2);
|
||||
if (data.activityHistory != null) {
|
||||
master["activityHistory"]["loadActivityData"](data.activityHistory);
|
||||
master["vipTime"] = data.activityHistory.vipInfo.vipTime;
|
||||
}
|
||||
if (data.payInfo != null) {
|
||||
if (data.payInfo.payPoint != null) master["history"]["payPoint"] = data.payInfo.payPoint;
|
||||
var giftTypes:Object = data.payInfo.payGiftTypes == null ? data.payInfo.payGitfTypes : data.payInfo.payGiftTypes;
|
||||
if (giftTypes != null) for each (key in String(giftTypes).split(",")) master["history"]["payGiftTypes"][key] = true;
|
||||
}
|
||||
master["globalAdd"]["update"](rawMaster);
|
||||
if (data.masterEventTimer != null) master["randomEventTimer"] = data.masterEventTimer;
|
||||
if (data.masterCurrentEvent != null) master["randomEvent"] = data.masterCurrentEvent;
|
||||
for each (row in monsters) {
|
||||
var mon:Object = monsterCenter["getMonByMonData"](row);
|
||||
// center/MasterCenter.as:loadMasterData only updates an
|
||||
// existing allMbs[mon.id]; [] and absent per-instance rows
|
||||
// intentionally preserve the original MonsterAdd defaults.
|
||||
if (attrById.hasOwnProperty(String(row.id))) mon["abilityAdd"]["update"](attrById[String(row.id)]);
|
||||
master["monsters"].push(mon);
|
||||
}
|
||||
for each (row in items) master["bag"]["items"].push(bagCenter["getItemByItemData"](row));
|
||||
var selectedTeam:Object = null;
|
||||
for each (row in teams) {
|
||||
var team:Object = teamCenter["getTeamVoByData"](row);
|
||||
master["teams"].push(team);
|
||||
if (row.teamName == teamName) selectedTeam = team;
|
||||
}
|
||||
for each (pos in selectedSlots)
|
||||
if (selectedTeam.monsters[pos] != rawTeam.monsters[pos])
|
||||
reject("team_slot", "teams", "original loader shifted an occupied selected slot");
|
||||
return {master:master, selectedTeam:selectedTeam, validation:{schema:1,
|
||||
source:"original_loadMasterData", teamName:teamName, teamType:rawTeam.teamType,
|
||||
selectedIds:selectedIds, selectedSlots:selectedSlots, rawSlots:rawTeam.monsters.concat(),
|
||||
monsterCount:monsters.length, attributeCount:attributes.length, itemCount:items.length,
|
||||
masterLevel:master["level"], ap:master["ap"], apSource:"MasterVo.ap/GameMath.apByLevel",
|
||||
historyLoader:"HistoryVo.loadHistoryData", installed:true}};
|
||||
} catch (error:Error) {
|
||||
game["master"] = previous;
|
||||
reject("original_loader", "snapshot", error.name + ": " + error.message);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static function validateHistory(data:Object):void {
|
||||
var h:Object = objectAt(data.history, "history");
|
||||
// Exact required shapes read by HistoryVo.loadHistoryData. Original
|
||||
// conversions produce guide/unlock/pass boolean maps, not arrays.
|
||||
for each (var name:String in ["monLib", "equipLib", "passAchi", "guide_record", "unlockCity"])
|
||||
arrayAt(h[name], "history." + name);
|
||||
for each (name in ["numFeedMonsters", "numKillMonsters", "historyGacha", "passTask", "unlockTask",
|
||||
"loopTask", "unlockStage", "passStage", "payTypeCount", "everyDayBuyProductNum"])
|
||||
objectAt(h[name], "history." + name);
|
||||
numbers(h, ["numAddMoney", "numChicken", "countBattle"], "history");
|
||||
for each (name in ["unlockStage", "passStage"])
|
||||
for (var key:String in h[name]) if (key != "") arrayAt(h[name][key], "history." + name + "." + key);
|
||||
if (data.data2 != null) {
|
||||
objectAt(data.data2, "data2"); arrayAt(data.data2.unlockSkins, "data2.unlockSkins");
|
||||
}
|
||||
if (data.activityHistory != null) {
|
||||
var activity:Object = objectAt(data.activityHistory, "activityHistory");
|
||||
var daily:Object = objectAt(activity.dailyGift, "activityHistory.dailyGift");
|
||||
numbers(daily, ["dailyGiftCheckTime", "dailyGiftLevel", "dailyGiftCount", "signCount"], "activityHistory.dailyGift");
|
||||
}
|
||||
}
|
||||
|
||||
private static function definition(domain:ApplicationDomain, name:String):Class {
|
||||
if (!domain.hasDefinition(name)) reject("definition", name, "original library definition is missing");
|
||||
return domain.getDefinition(name) as Class;
|
||||
}
|
||||
private static function objectAt(value:Object, path:String):Object {
|
||||
if (value == null || typeof(value) != "object" || value is Array)
|
||||
reject("missing_object", path, "expected an explicit object");
|
||||
return value;
|
||||
}
|
||||
private static function arrayAt(value:Object, path:String):Array {
|
||||
if (!(value is Array)) reject("missing_array", path, "expected an explicit array, including when empty");
|
||||
return value as Array;
|
||||
}
|
||||
private static function numberAt(value:Object, path:String):Number {
|
||||
if (value == null || typeof(value) != "number" || !isFinite(Number(value)))
|
||||
reject("missing_number", path, "expected an explicit finite number; no stat defaults are supplied");
|
||||
return Number(value);
|
||||
}
|
||||
private static function numbers(row:Object, names:Array, path:String):void {
|
||||
for each (var name:String in names) numberAt(row[name], path + "." + name);
|
||||
}
|
||||
private static function positiveId(value:Object, path:String, max:Number = 9007199254740991):void {
|
||||
var n:Number = numberAt(value, path);
|
||||
if (n < 1 || n != Math.floor(n) || n > max) reject("positive_integer", path, "expected an exact positive integer within the original field range");
|
||||
}
|
||||
private static function flag(value:Object, path:String):void {
|
||||
if (!(value is Boolean) && !(value === 0 || value === 1)) reject("missing_flag", path, "expected explicit boolean or 0/1 flag");
|
||||
}
|
||||
private static function jsonObject(value:Object, path:String):Object {
|
||||
if (!(value is String)) reject("json_string", path, "original loader requires a JSON object string");
|
||||
var decoded:Object;
|
||||
try { decoded = JSON.parse(String(value)); }
|
||||
catch (error:Error) { reject("json_string", path, "invalid JSON object string"); }
|
||||
return objectAt(decoded, path);
|
||||
}
|
||||
private static function copy(value:Object):Object {
|
||||
if (value == null || typeof(value) != "object") return value;
|
||||
var result:Object = value is Array ? [] : {};
|
||||
for (var key:String in value) result[key] = copy(value[key]);
|
||||
return result;
|
||||
}
|
||||
private static function reject(code:String, path:String, message:String):void {
|
||||
throw new Error("SnapshotBridge[" + code + "] " + path + ": " + message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Fetch only compiler/desktop-runtime members from the official AIR SDK ZIP.
|
||||
|
||||
Opt-in dependency acquisition, never imported by the offline adapter. Everything
|
||||
is scoped to ignored local_state; the SDK is not installed or placed on PATH.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import http.cookiejar
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import urllib.request
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BASE = "https://airsdk.wxlift.com"
|
||||
SDK_VERSION = "51.5.1.1" # Must match the reviewed executable hashes in trusted.py.
|
||||
|
||||
|
||||
class RemoteZip(io.RawIOBase):
|
||||
def __init__(self, opener, url):
|
||||
self.opener, self.url, self.position = opener, url, 0
|
||||
self.cached_start, self.cached_data = 0, b""
|
||||
with self.fetch(0, 1) as response:
|
||||
self.size = int(response.headers["Content-Range"].split("/")[-1])
|
||||
|
||||
def fetch(self, start, size):
|
||||
return self.opener.open(urllib.request.Request(self.url, headers={
|
||||
"Range": f"bytes={start}-{start + size - 1}",
|
||||
"Referer": BASE + "/download"}), timeout=45)
|
||||
|
||||
def seekable(self):
|
||||
return True
|
||||
|
||||
def seek(self, offset, whence=0):
|
||||
self.position = offset + (0 if whence == 0 else self.position if whence == 1 else self.size)
|
||||
return self.position
|
||||
|
||||
def tell(self):
|
||||
return self.position
|
||||
|
||||
def read(self, size=-1):
|
||||
size = min(self.size - self.position, size if size >= 0 else self.size)
|
||||
if size <= 0:
|
||||
return b""
|
||||
if self.cached_start <= self.position and self.position + size <= self.cached_start + len(self.cached_data):
|
||||
offset = self.position - self.cached_start
|
||||
self.position += size
|
||||
return self.cached_data[offset:offset + size]
|
||||
requested = min(self.size - self.position, max(size, 128 * 1024))
|
||||
with self.fetch(self.position, requested) as response:
|
||||
if response.status != 206:
|
||||
raise ValueError("Official SDK server did not honor byte range")
|
||||
fetched = response.read()
|
||||
if len(fetched) != requested:
|
||||
raise ValueError("Truncated SDK byte range")
|
||||
self.cached_start, self.cached_data = self.position, fetched
|
||||
data = fetched[:size]
|
||||
self.position += size
|
||||
return data
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--list", action="store_true")
|
||||
parser.add_argument("--runtime-only", action="store_true")
|
||||
args = parser.parse_args()
|
||||
root = ROOT / "local_state/battle_runtime"
|
||||
acquisition = root / "acquisition"
|
||||
acquisition.mkdir(parents=True, exist_ok=True)
|
||||
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
|
||||
with opener.open(BASE + "/api/config-settings/download", timeout=30) as response:
|
||||
settings = json.load(response)
|
||||
link = f"/api/versions/{SDK_VERSION}/sdks/AIRSDK_Windows.zip"
|
||||
url = BASE + link + "?id=" + str(settings["id"])
|
||||
remote = RemoteZip(opener, url)
|
||||
with zipfile.ZipFile(remote) as archive:
|
||||
inventory = [{"name": item.filename, "bytes": item.file_size,
|
||||
"compressed": item.compress_size, "crc32": item.CRC}
|
||||
for item in archive.infolist()]
|
||||
(acquisition / "sdk_inventory.json").write_text(json.dumps(inventory, indent=2), encoding="utf-8")
|
||||
selected = [item for item in archive.infolist() if not item.is_dir() and (
|
||||
item.filename.startswith("runtimes/air/win64/")
|
||||
or (item.filename.startswith("lib/") and item.filename.count("/") == 1)
|
||||
or (item.filename.startswith("frameworks/") and not item.filename.startswith(("frameworks/projects/", "frameworks/locale/")))
|
||||
or item.filename in ("bin/adl.exe", "bin/adl64.exe", "air-sdk-description.xml"))]
|
||||
if args.runtime_only:
|
||||
selected = [item for item in selected if item.filename.startswith("runtimes/") or item.filename == "bin/adl64.exe"]
|
||||
print(json.dumps({"version": SDK_VERSION, "archive_bytes": remote.size,
|
||||
"selected_files": len(selected), "selected_compressed_bytes": sum(i.compress_size for i in selected)}), flush=True)
|
||||
if args.list:
|
||||
for item in selected:
|
||||
print(item.filename, item.file_size)
|
||||
return
|
||||
destination = root / "air_sdk"
|
||||
identity = {"version": SDK_VERSION, "source": BASE + link, "files": {}}
|
||||
for item in selected:
|
||||
path = (destination / item.filename).resolve()
|
||||
if not path.is_relative_to(destination.resolve()):
|
||||
raise ValueError("SDK path escapes local destination")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
existing = path.read_bytes() if path.is_file() else b""
|
||||
data = existing if len(existing) == item.file_size and zlib.crc32(existing) == item.CRC else archive.read(item)
|
||||
path.write_bytes(data)
|
||||
identity["files"][item.filename] = hashlib.sha256(data).hexdigest()
|
||||
print(item.filename, len(data), flush=True)
|
||||
(acquisition / "sdk_identity.json").write_text(json.dumps(identity, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,390 @@
|
||||
"""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}}
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Bounded child-process supervision. No runner command comes from a policy file."""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Sequence
|
||||
|
||||
|
||||
class _WindowsJob:
|
||||
"""Close a private job to kill the worker and any ADL/compiler descendants."""
|
||||
def __init__(self, process):
|
||||
class Basic(ctypes.Structure):
|
||||
_fields_ = [("process_time", ctypes.c_longlong), ("job_time", ctypes.c_longlong),
|
||||
("flags", wintypes.DWORD), ("minimum_working_set", ctypes.c_size_t),
|
||||
("maximum_working_set", ctypes.c_size_t), ("active_processes", wintypes.DWORD),
|
||||
("affinity", ctypes.c_size_t), ("priority", wintypes.DWORD),
|
||||
("scheduling", wintypes.DWORD)]
|
||||
|
||||
class IO(ctypes.Structure):
|
||||
_fields_ = [(name, ctypes.c_ulonglong) for name in (
|
||||
"read_ops", "write_ops", "other_ops", "read_bytes", "write_bytes", "other_bytes")]
|
||||
|
||||
class Extended(ctypes.Structure):
|
||||
_fields_ = [("basic", Basic), ("io", IO), ("process_memory", ctypes.c_size_t),
|
||||
("job_memory", ctypes.c_size_t), ("peak_process_memory", ctypes.c_size_t),
|
||||
("peak_job_memory", ctypes.c_size_t)]
|
||||
|
||||
self.kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
self.kernel.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
|
||||
self.kernel.CreateJobObjectW.restype = wintypes.HANDLE
|
||||
self.kernel.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]
|
||||
self.kernel.SetInformationJobObject.restype = wintypes.BOOL
|
||||
self.kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
|
||||
self.kernel.AssignProcessToJobObject.restype = wintypes.BOOL
|
||||
self.kernel.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
self.kernel.CloseHandle.restype = wintypes.BOOL
|
||||
self.handle = self.kernel.CreateJobObjectW(None, None)
|
||||
if not self.handle:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
limits = Extended()
|
||||
limits.basic.flags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
if not self.kernel.SetInformationJobObject(self.handle, 9, ctypes.byref(limits), ctypes.sizeof(limits)):
|
||||
code = ctypes.get_last_error(); self.close(); raise ctypes.WinError(code)
|
||||
if not self.kernel.AssignProcessToJobObject(self.handle, wintypes.HANDLE(int(process._handle))):
|
||||
code = ctypes.get_last_error(); self.close(); raise ctypes.WinError(code)
|
||||
|
||||
def close(self):
|
||||
if self.handle:
|
||||
self.kernel.CloseHandle(self.handle)
|
||||
self.handle = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProcessResult:
|
||||
status: str
|
||||
returncode: int | None
|
||||
duration_seconds: float
|
||||
stdout: str
|
||||
stderr: str
|
||||
|
||||
|
||||
def run_isolated(argv: Sequence[str], *, cwd: Path, timeout: float, cancel_event=None,
|
||||
output_limit: int = 2 * 1024 * 1024) -> ProcessResult:
|
||||
"""Use only with bundled fixed commands; never forward imported argv/config.
|
||||
|
||||
Separate cwd/logs, shell=False, no inherited stdin, no visible helper window,
|
||||
a wall-clock deadline, and a kill-on-close process tree on Windows. This is
|
||||
process/lifetime isolation, not an OS network sandbox.
|
||||
"""
|
||||
if isinstance(timeout, bool) or not isinstance(timeout, (float, int)) or not math.isfinite(timeout) or timeout <= 0:
|
||||
raise ValueError("timeout must be a finite positive number")
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
return ProcessResult("cancelled", None, 0.0, "", "")
|
||||
cwd.mkdir(parents=True, exist_ok=True)
|
||||
stdout_path, stderr_path = cwd / "worker.stdout.log", cwd / "worker.stderr.log"
|
||||
started = time.monotonic()
|
||||
process, job, status = None, None, "error"
|
||||
with stdout_path.open("wb") as stdout, stderr_path.open("wb") as stderr:
|
||||
try:
|
||||
process = subprocess.Popen(list(argv), cwd=cwd, stdin=subprocess.DEVNULL, stdout=stdout,
|
||||
stderr=stderr, shell=False, close_fds=True,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||
start_new_session=os.name != "nt")
|
||||
if os.name == "nt":
|
||||
job = _WindowsJob(process)
|
||||
while process.poll() is None:
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
status = "cancelled"; break
|
||||
if time.monotonic() - started >= timeout:
|
||||
status = "timeout"; break
|
||||
if stdout_path.stat().st_size + stderr_path.stat().st_size > output_limit:
|
||||
status = "output_limit"; break
|
||||
time.sleep(.025)
|
||||
else:
|
||||
status = "completed" if process.returncode == 0 else "error"
|
||||
except OSError as error:
|
||||
stderr.write(str(error).encode("utf-8", errors="replace"))
|
||||
finally:
|
||||
if job is not None:
|
||||
job.close()
|
||||
elif process is not None and os.name != "nt":
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
if process is not None:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
def bounded(path):
|
||||
with path.open("rb") as stream:
|
||||
return stream.read(output_limit).decode("utf-8", errors="replace")
|
||||
return ProcessResult(status, process.returncode if process is not None else None,
|
||||
time.monotonic() - started, bounded(stdout_path), bounded(stderr_path))
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Recover original offline libraries and tables from the pinned local APK."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from ranch_assistant.amf import Reader
|
||||
from tools.battle_runtime.swf_library import digest, library_only
|
||||
|
||||
APK_SHA256 = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d"
|
||||
MAIN_SHA256 = "c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf"
|
||||
TABLES = ("setting", "game_setting", "monster_info", "monster_skill", "monster_setting",
|
||||
"monster_level", "monster_fix", "team_info", "stage_info", "task_info",
|
||||
"item_info", "potential_info", "entangle_info", "skin_info", "upstar_info")
|
||||
|
||||
|
||||
def write_atomic(path: Path, data: bytes):
|
||||
# Prepared resources are immutable for the pinned APK. Reusing identical
|
||||
# bytes also avoids Windows rename failures while another AIR job reads a
|
||||
# shared resource (each job still has its own application/storage/cwd).
|
||||
if path.is_file() and path.read_bytes() == data:
|
||||
return
|
||||
temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp")
|
||||
try:
|
||||
temporary.write_bytes(data)
|
||||
try:
|
||||
temporary.replace(path)
|
||||
except PermissionError:
|
||||
# Another preparer may have published the exact same bytes after
|
||||
# our first check. Never accept a different or partially read file.
|
||||
if not path.is_file() or path.read_bytes() != data:
|
||||
raise
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def write_json(path: Path, data):
|
||||
write_atomic(path, json.dumps(data, ensure_ascii=False, allow_nan=False, indent=2).encode("utf-8"))
|
||||
|
||||
|
||||
def asset_index(apk: Path, archive: zipfile.ZipFile) -> dict:
|
||||
"""Bind original packed-resource keys to their verified ZIP byte ranges."""
|
||||
entries = {}
|
||||
archive_size = apk.stat().st_size
|
||||
with apk.open("rb") as source:
|
||||
for item in archive.infolist():
|
||||
if not item.filename.startswith("assets/codes/") or item.is_dir():
|
||||
continue
|
||||
key = item.filename.removeprefix("assets/codes/")
|
||||
if len(key) != 32 or any(c not in "0123456789abcdef" for c in key) or item.flag_bits & 1 or item.compress_type not in (0,8):
|
||||
raise ValueError("Unsupported original asset ZIP member")
|
||||
if key in entries:
|
||||
raise ValueError("Duplicate original asset ZIP member")
|
||||
source.seek(item.header_offset)
|
||||
header = source.read(30)
|
||||
if len(header) != 30 or header[:4] != b"PK\x03\x04":
|
||||
raise ValueError("Original ZIP local header mismatch")
|
||||
flags, method = struct.unpack_from("<HH",header,6)
|
||||
if flags != item.flag_bits or method != item.compress_type:
|
||||
raise ValueError("Original ZIP local metadata mismatch")
|
||||
filename_size, extra_size = struct.unpack_from("<HH", header, 26)
|
||||
encoded_name = source.read(filename_size)
|
||||
if encoded_name.decode("utf-8" if flags & 0x800 else "cp437") != item.filename:
|
||||
raise ValueError("Original ZIP local filename mismatch")
|
||||
offset = item.header_offset + 30 + filename_size + extra_size
|
||||
if offset < 0 or offset + item.compress_size > archive_size:
|
||||
raise ValueError("Original asset ZIP member escapes archive")
|
||||
entries[key] = {"offset":offset,"compressed_size":item.compress_size,
|
||||
"size":item.file_size,"method":item.compress_type,"crc32":item.CRC}
|
||||
return entries
|
||||
|
||||
|
||||
def prepare(apk: Path | None = None, *, assets: bool = False) -> dict:
|
||||
if apk is None:
|
||||
candidates = list(ROOT.glob("*_1.9.68.apk"))
|
||||
if len(candidates) != 1:
|
||||
raise ValueError("Expected exactly one original *_1.9.68.apk")
|
||||
apk = candidates[0]
|
||||
with apk.open("rb") as stream:
|
||||
sha = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if sha != APK_SHA256:
|
||||
raise ValueError("Original APK SHA-256 mismatch")
|
||||
root = ROOT / "local_state/battle_runtime/original"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
manifest = {"apk_sha256": sha, "main_swf_sha256": MAIN_SHA256, "libraries": {}, "tables": {}}
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
entries = asset_index(apk,archive)
|
||||
write_json(root / "asset_index.json", {"apk_path":str(apk.resolve()),"apk_sha256":sha,"entries":entries})
|
||||
manifest["asset_index_sha256"] = digest((root / "asset_index.json").read_bytes())
|
||||
for member, filename in (("assets/MYRDyd.swf", "framework.library.swf"),
|
||||
("assets/MYRMain.app", "main.library.swf")):
|
||||
original = archive.read(member)
|
||||
if member.endswith("MYRMain.app") and digest(original) != MAIN_SHA256:
|
||||
raise ValueError("Original main SWF SHA-256 mismatch")
|
||||
library, identity = library_only(original)
|
||||
write_atomic(root / filename, library)
|
||||
manifest["libraries"][filename] = identity
|
||||
tables = {}
|
||||
(root / "tables").mkdir(exist_ok=True)
|
||||
for name in TABLES:
|
||||
member = "assets/codes/" + hashlib.md5(f"data/table/{name}.json".encode()).hexdigest()
|
||||
if member not in archive.namelist():
|
||||
manifest["tables"][name] = {"missing": True}
|
||||
continue
|
||||
compressed = archive.read(member)
|
||||
write_atomic(root / "tables" / (name + ".amf.zlib"), compressed)
|
||||
decoded = zlib.decompress(compressed)
|
||||
reader = Reader(decoded)
|
||||
value = reader.read()
|
||||
if reader.pos != len(decoded):
|
||||
raise ValueError(f"Trailing original table bytes: {name}")
|
||||
tables[name] = value
|
||||
manifest["tables"][name] = {"member": member, "sha256": digest(compressed)}
|
||||
write_json(root / "tables.json", tables)
|
||||
write_json(root / "table_index.json", list(tables))
|
||||
manifest["tables_json_sha256"] = digest((root / "tables.json").read_bytes())
|
||||
# Preserve actual libraries/assets locally. No APK is rebuilt or installed.
|
||||
for member in ("assets/baseui.swf", "assets/ui/mainui.swf", "assets/ui/mainui2.swf",
|
||||
"assets/ui/mainui3.swf", "assets/ui/movieclip.swf"):
|
||||
original = archive.read(member)
|
||||
library, identity = library_only(original)
|
||||
path = root / (Path(member).stem + ".library.swf")
|
||||
write_atomic(path, library)
|
||||
manifest["libraries"][path.name] = identity
|
||||
if assets:
|
||||
asset_count = asset_bytes = 0
|
||||
destination = root / "codes"
|
||||
destination.mkdir(exist_ok=True)
|
||||
for item in archive.infolist():
|
||||
if item.filename.startswith("assets/codes/") and not item.is_dir():
|
||||
basename = item.filename.removeprefix("assets/codes/")
|
||||
if len(basename) != 32 or any(c not in "0123456789abcdef" for c in basename):
|
||||
raise ValueError("Unexpected original asset member")
|
||||
path = destination / basename
|
||||
if not path.exists() or path.stat().st_size != item.file_size:
|
||||
write_atomic(path, archive.read(item))
|
||||
asset_count += 1
|
||||
asset_bytes += item.file_size
|
||||
write_json(root / "assets_prepared.json", {"count":asset_count,"bytes":asset_bytes,
|
||||
"source_apk_sha256":sha})
|
||||
manifest["asset_count"] = asset_count
|
||||
write_json(root / "identity.json", manifest)
|
||||
return manifest
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apk", type=Path)
|
||||
parser.add_argument("--assets", action="store_true")
|
||||
args = parser.parse_args()
|
||||
manifest = prepare(args.apk, assets=args.assets)
|
||||
print(json.dumps({"main_swf_sha256": manifest["main_swf_sha256"],
|
||||
"libraries": {name: {k: v for k, v in row.items() if k in (
|
||||
"removed_document_classes", "abc_count", "lazy_flags_changed", "abc_bytes_preserved")}
|
||||
for name, row in manifest["libraries"].items()}}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<application xmlns="http://ns.adobe.com/air/application/51.1">
|
||||
<id>local.ranchassistant.originalprobe</id>
|
||||
<versionNumber>0.0.1</versionNumber>
|
||||
<filename>OriginalProbe</filename>
|
||||
<initialWindow>
|
||||
<content>OriginalProbe.swf</content>
|
||||
<visible>false</visible>
|
||||
<width>640</width><height>960</height>
|
||||
<systemChrome>none</systemChrome>
|
||||
<renderMode>cpu</renderMode>
|
||||
</initialWindow>
|
||||
<supportedProfiles>extendedDesktop</supportedProfiles>
|
||||
</application>
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Compile and execute the fixed original-library probe (no network imports)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SOURCE = Path(__file__).resolve().parent
|
||||
LOCAL = ROOT / "local_state/battle_runtime"
|
||||
|
||||
|
||||
def compile_probe(build_directory: Path | None = None) -> dict:
|
||||
sdk = LOCAL / "air_sdk"
|
||||
build = build_directory if build_directory is not None else LOCAL / "build"
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
captured_source = build / "source"
|
||||
captured_source.mkdir(exist_ok=True)
|
||||
source_bytes = (SOURCE / "OriginalProbe.as").read_bytes()
|
||||
(captured_source / "OriginalProbe.as").write_bytes(source_bytes)
|
||||
bridge = SOURCE / "SnapshotBridge.as"
|
||||
bridge_bytes = bridge.read_bytes() if bridge.is_file() else None
|
||||
if bridge_bytes is not None:
|
||||
(captured_source / "SnapshotBridge.as").write_bytes(bridge_bytes)
|
||||
config = build / "compiler-config.xml"
|
||||
config.write_text("<flex-config/>", encoding="utf-8")
|
||||
command = [shutil.which("java") or "java", "-Duser.language=en", "-Duser.country=US", "-jar", str(sdk / "lib/mxmlc-cli.jar"),
|
||||
"-load-config=" + str(config), "-compiler.external-library-path=" + str(sdk / "frameworks/libs/air/airglobal.swc"),
|
||||
"-compiler.library-path=" + str(sdk / "frameworks/libs/core.swc"),
|
||||
"-swf-version=50", "-debug=true", "-default-frame-rate=50", "-default-size=640,960",
|
||||
"-output=" + str(build / "OriginalProbe.swf"), str(captured_source / "OriginalProbe.as")]
|
||||
if bridge_bytes is not None:
|
||||
command.insert(-1, "-source-path=" + str(captured_source))
|
||||
command.insert(-1, "-includes=SnapshotBridge")
|
||||
result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
evidence = {"command": command, "exit_code": result.returncode, "stdout": result.stdout, "stderr": result.stderr,
|
||||
"source_sha256": hashlib.sha256(source_bytes).hexdigest()}
|
||||
(build / "compile.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError("AIR harness compile failed: " + result.stdout + result.stderr)
|
||||
shutil.copyfile(SOURCE / "probe-app.xml", build / "probe-app.xml")
|
||||
descriptor = build / "probe-app.xml"
|
||||
descriptor.write_text(descriptor.read_text(encoding="utf-8").replace(
|
||||
"local.ranchassistant.originalprobe", "local.ranchassistant.originalprobe.j" + uuid.uuid4().hex), encoding="utf-8")
|
||||
evidence["swf_sha256"] = hashlib.sha256((build / "OriginalProbe.swf").read_bytes()).hexdigest()
|
||||
if bridge_bytes is not None:
|
||||
evidence["snapshot_bridge_sha256"] = hashlib.sha256(bridge_bytes).hexdigest()
|
||||
return evidence
|
||||
|
||||
|
||||
def execute_probe(*, timeout: float = 690.0, cancel_event=None, scene: bool = False, source_request: dict | None = None) -> dict:
|
||||
# Re-derive all original libraries rather than accepting imported manifest claims.
|
||||
from tools.battle_runtime.prepare import prepare
|
||||
from tools.battle_runtime.trusted import SDK_FILES, LIBRARY_FILES, verify_files
|
||||
dependency_errors = verify_files(LOCAL / "air_sdk", SDK_FILES)
|
||||
if dependency_errors:
|
||||
raise RuntimeError("Untrusted/missing AIR dependencies: " + json.dumps(dependency_errors))
|
||||
identity = prepare()
|
||||
validation = None
|
||||
if source_request is not None:
|
||||
from tools.battle_runtime.inputs import validate
|
||||
validation = validate(source_request)
|
||||
if validation["reasons"]:
|
||||
raise ValueError("Original request refused: " + json.dumps(validation["reasons"]))
|
||||
attempt = LOCAL / "experiments" / uuid.uuid4().hex
|
||||
attempt.mkdir(parents=True)
|
||||
compiler = compile_probe(attempt / "build")
|
||||
library_errors = verify_files(LOCAL / "original", LIBRARY_FILES)
|
||||
if library_errors:
|
||||
raise RuntimeError("Original library identity mismatch: " + json.dumps(library_errors))
|
||||
request = attempt / "request.json"
|
||||
nonce = uuid.uuid4().hex
|
||||
native_request = validation["native_request"] if validation is not None else {"stage_id":"0101","difficulty":1,"scene":scene}
|
||||
native_request = dict(native_request,nonce=nonce,watchdog_ms=int(timeout*1000))
|
||||
request.write_text(json.dumps(native_request,ensure_ascii=False,allow_nan=False), encoding="utf-8")
|
||||
sdk = LOCAL / "air_sdk"
|
||||
command = [str(sdk / "bin/adl64.exe"), "-runtime", str(sdk / "runtimes/air/win64"), "-nodebug",
|
||||
"-profile", "extendedDesktop", str(attempt / "build/probe-app.xml"),
|
||||
"--", str(LOCAL / "original"), str(request), str(attempt / "result.json")]
|
||||
started = time.monotonic()
|
||||
with (attempt / "stdout.log").open("wb") as stdout, (attempt / "stderr.log").open("wb") as stderr:
|
||||
process = subprocess.Popen(command, cwd=attempt, stdout=stdout, stderr=stderr,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
interrupted = None
|
||||
try:
|
||||
while process.poll() is None:
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
interrupted = "cancelled"; break
|
||||
if time.monotonic() - started >= timeout:
|
||||
interrupted = "timeout"; break
|
||||
time.sleep(.05)
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
result_file = attempt / "result.json"
|
||||
result = json.loads(result_file.read_text(encoding="utf-8")) if result_file.exists() and not interrupted else {
|
||||
"status": interrupted or "process_failed", "battle_executed": None, "settlement_eligible": False}
|
||||
if result_file.exists() and not interrupted and result.get("nonce") != nonce:
|
||||
raise ValueError("Native AIR result nonce mismatch")
|
||||
audit = audit_resources(result)
|
||||
evidence = {"command": command, "compiler": compiler, "process_exit_code": process.returncode,
|
||||
"duration_seconds": time.monotonic() - started, "result": result,
|
||||
"resource_identity": {"apk_sha256": identity["apk_sha256"],
|
||||
"main_swf_sha256": identity["main_swf_sha256"]},
|
||||
"resource_audit": audit,
|
||||
"input_sha256":hashlib.sha256(json.dumps(source_request,ensure_ascii=True,allow_nan=False,sort_keys=True,separators=(",", ":")).encode("ascii")).hexdigest() if source_request is not None else None,
|
||||
"directory": str(attempt)}
|
||||
(attempt / "evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")
|
||||
return evidence
|
||||
|
||||
|
||||
def audit_resources(result: dict) -> dict:
|
||||
"""Compare every read image with the pinned APK; retain genuine absences."""
|
||||
import zipfile
|
||||
reads = [event["data"] for event in result.get("events", []) if event.get("kind") == "original_asset_read"]
|
||||
members = {read["member"] for read in reads}
|
||||
candidates = list(ROOT.glob("*_1.9.68.apk"))
|
||||
if len(candidates) != 1:
|
||||
raise ValueError("Ambiguous original APK during resource audit")
|
||||
missing, mismatched = [], []
|
||||
with zipfile.ZipFile(candidates[0]) as archive:
|
||||
names = set(archive.namelist())
|
||||
for member in sorted(members):
|
||||
if not member.startswith("codes/") or len(member) != 38 or any(c not in "0123456789abcdef" for c in member[6:]):
|
||||
raise ValueError("Invalid resource identity in original trace")
|
||||
if "assets/" + member not in names:
|
||||
missing.append(member)
|
||||
if any(read.get("crc32") is not None for read in reads if read["member"] == member):
|
||||
mismatched.append(member)
|
||||
else:
|
||||
info = archive.getinfo("assets/" + member)
|
||||
if any(read.get("crc32") != info.CRC or read.get("bytes") != info.file_size for read in reads if read["member"] == member):
|
||||
mismatched.append(member)
|
||||
return {"used_asset_count":len(members), "original_missing_members":missing,
|
||||
"mismatched_members":mismatched, "all_present_assets_match_apk":not mismatched}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compile-only", action="store_true")
|
||||
parser.add_argument("--scene", action="store_true")
|
||||
args = parser.parse_args()
|
||||
if args.compile_only:
|
||||
print(json.dumps(compile_probe(), indent=2))
|
||||
else:
|
||||
print(json.dumps(execute_probe(scene=args.scene), indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.path.insert(0, str(ROOT))
|
||||
main()
|
||||
@@ -0,0 +1,376 @@
|
||||
"""Offline, synthetic-only AIR checks for SnapshotBridge; never starts the game.
|
||||
|
||||
Generated AS3, SWFs, requests and results stay in the ignored local runtime
|
||||
directory. The harness only loads the already prepared library SWFs and tables.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SOURCE = Path(__file__).resolve().parent
|
||||
LOCAL = ROOT / "local_state/battle_runtime"
|
||||
|
||||
HARNESS = r'''
|
||||
package {
|
||||
import flash.desktop.NativeApplication;
|
||||
import flash.display.Loader;
|
||||
import flash.display.Sprite;
|
||||
import flash.events.Event;
|
||||
import flash.events.IOErrorEvent;
|
||||
import flash.events.InvokeEvent;
|
||||
import flash.events.UncaughtErrorEvent;
|
||||
import flash.filesystem.File;
|
||||
import flash.filesystem.FileMode;
|
||||
import flash.filesystem.FileStream;
|
||||
import flash.system.ApplicationDomain;
|
||||
import flash.system.LoaderContext;
|
||||
import flash.utils.ByteArray;
|
||||
import flash.utils.describeType;
|
||||
public class SnapshotBridgeCheck extends Sprite {
|
||||
private var domain:ApplicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
|
||||
private var names:Array = ["framework", "main", "baseui", "mainui", "mainui2", "mainui3", "movieclip"];
|
||||
private var loaders:Array = [];
|
||||
private var index:int = 0;
|
||||
private var root:File;
|
||||
private var output:File;
|
||||
private var request:Object;
|
||||
private var finished:Boolean = false;
|
||||
private var frameworkReady:Boolean = false;
|
||||
public function SnapshotBridgeCheck() {
|
||||
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR,
|
||||
function(e:UncaughtErrorEvent):void {
|
||||
e.preventDefault(); finish({ok:false, error:String(e.error)});
|
||||
});
|
||||
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, invoke);
|
||||
}
|
||||
private function invoke(e:InvokeEvent):void {
|
||||
try {
|
||||
root = new File(e.arguments[0]); output = new File(e.arguments[2]);
|
||||
request = JSON.parse(readText(new File(e.arguments[1])));
|
||||
loadNext();
|
||||
} catch (error:Error) { finish({ok:false,error:error.getStackTrace() || error.toString()}); }
|
||||
}
|
||||
private function readText(file:File):String {
|
||||
var s:FileStream = new FileStream(); s.open(file,FileMode.READ);
|
||||
var text:String = s.readUTFBytes(s.bytesAvailable); s.close(); return text;
|
||||
}
|
||||
private function readBytes(file:File):ByteArray {
|
||||
var s:FileStream = new FileStream(); s.open(file,FileMode.READ);
|
||||
var bytes:ByteArray = new ByteArray(); s.readBytes(bytes); s.close(); return bytes;
|
||||
}
|
||||
private function cls(name:String):Class { return domain.getDefinition(name) as Class; }
|
||||
private function loadNext():void {
|
||||
if (index == names.length) { check(); return; }
|
||||
var loader:Loader = new Loader(); loaders.push(loader);
|
||||
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(e:Event):void { loadNext(); });
|
||||
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,
|
||||
function(e:IOErrorEvent):void { finish({ok:false,error:e.text}); });
|
||||
var context:LoaderContext = new LoaderContext(false,domain); context.allowCodeImport = true;
|
||||
loader.loadBytes(readBytes(root.resolvePath(names[index++] + ".library.swf")),context);
|
||||
}
|
||||
private function check():void {
|
||||
try {
|
||||
var table:Class = cls("net.pixvi.myr.center.Table");
|
||||
var names:Array = JSON.parse(readText(root.resolvePath("table_index.json"))) as Array;
|
||||
var rm:Class = cls("net.pixvi.common.manager.resource.RM"); rm["getInstance"]();
|
||||
var stringLoader:Class = cls("net.pixvi.pfw.net.PiStringLoader");
|
||||
stringLoader["globalCryptoMode"] = true;
|
||||
stringLoader["globalJsonCryptoModeFunction"] = cls("net.pixvi.myrcryptor.MYRCryptor")["jsonDecodeHandler"];
|
||||
var resourceClass:Class = cls("net.pixvi.common.net.resource.ResourceVo");
|
||||
for each (var name:String in names) {
|
||||
var packed:ByteArray = readBytes(root.resolvePath("tables/" + name + ".amf.zlib"));
|
||||
var resource:Object = new resourceClass("data/table/" + name + ".json");
|
||||
resource["crypto"] = true; resource["data"] = packed; rm["TXT"]["push"](resource);
|
||||
var bytes:ByteArray = readBytes(root.resolvePath("tables/" + name + ".amf.zlib"));
|
||||
bytes.uncompress(); bytes.objectEncoding = 3;
|
||||
var value:Object = bytes.readObject();
|
||||
table[name] = name != "team_info" && value.hasOwnProperty("datas") ? value.datas : value;
|
||||
// ORIGINAL Table.startUp flattens the skin resource wrapper.
|
||||
if (name == "skin_info") table[name] = value.skins;
|
||||
}
|
||||
table["monster_group"] = table["monster_setting"].group;
|
||||
table["monster_element"] = table["monster_setting"].element;
|
||||
__ACTION__
|
||||
} catch (error:Error) { finish({ok:false,error:error.getStackTrace() || error.toString()}); }
|
||||
}
|
||||
private function initializeFramework():void {
|
||||
if (!frameworkReady) {
|
||||
addChild(cls("net.pixvi.common.center.StartUpCenter")["startUp"](stage,true,false,false,false));
|
||||
var fixClass:Class = cls("net.pixvi.common.utils.PiFixVo");
|
||||
var fs1:Object = new fixClass(); fs1.id = "fs1"; fs1.maxHWScale = 1.775;
|
||||
var fs2:Object = new fixClass(); fs2.id = "fs2"; fs2.maxHWScale = 1.9125;
|
||||
cls("net.pixvi.common.utils.StageLocator")["autoFull"](720,1136,[fs1,fs2]);
|
||||
cls("net.pixvi.myr.battle.BattleGround")["firstStartUp"](); frameworkReady = true;
|
||||
}
|
||||
}
|
||||
private function integrity(roster:Object):Object {
|
||||
// Exercise BattlePanel's private cheatCheck through its ORIGINAL
|
||||
// public completion handler. Native units come from TeamCenter;
|
||||
// skip movie loading and install only local result callbacks.
|
||||
initializeFramework();
|
||||
var panelClass:Class = cls("net.pixvi.myr.panel.battle.BattlePanel");
|
||||
var panel:Object = panelClass["getIns"]();
|
||||
var groundClass:Class = cls("net.pixvi.myr.battle.BattleGround");
|
||||
var ground:Object = new groundClass(); panel.ground = ground;
|
||||
var battleClass:Class = cls("net.pixvi.myr.element.battle.BattleVo");
|
||||
var battle:Object = new battleClass(); ground.vo = battle; panel.battle = battle;
|
||||
var table:Class = cls("net.pixvi.myr.center.Table");
|
||||
var authored:Object = table["stage_info"];
|
||||
if (authored is Array) for each (var stageRow:Object in authored) {
|
||||
if (stageRow.id == "0101") { authored = {"0101":stageRow}; break; }
|
||||
}
|
||||
battle["buildByObject"](authored["0101"].level["1"].battle);
|
||||
var nativeTeam:Object = cls("net.pixvi.myr.center.TeamCenter")["getIns"]()["getBattleTeamVo"](roster.selectedTeam.teamName);
|
||||
battle.teamDic[1] = nativeTeam; battle.teams = [nativeTeam];
|
||||
var viewClass:Class = cls("net.pixvi.myr.battle.view.BattleMon");
|
||||
var skillClass:Class = cls("net.pixvi.myr.view.skill.SkillType");
|
||||
for (var i:int = 0; i < nativeTeam.mons.length; i++) {
|
||||
var nativeVo:Object = nativeTeam.mons[i];
|
||||
var view:Object = new viewClass();
|
||||
view.vo = nativeVo.monsterVo; view.monVo = nativeVo; view.teamVo = nativeTeam;
|
||||
// The pure skill portion of BattleMon.init, without buildView
|
||||
// or image/movie loading. Skill parameters stay in original code.
|
||||
view.skill_1 = skillClass["getSkill"](view.vo.skill_1,view.vo.skill_1_lv);
|
||||
view.skill_2 = skillClass["getSkill"](view.vo.skill_2,view.vo.skill_2_lv);
|
||||
if (view.skill_1 != null) view.skill_1["init"](view);
|
||||
if (view.skill_2 != null) view.skill_2["init"](view);
|
||||
nativeTeam.mons[i] = view;
|
||||
}
|
||||
var cooldownClass:Class = cls("net.pixvi.common.utils.Cooldowner");
|
||||
ground.battleTime = new cooldownClass(1000); ground.winnerTeam = 1;
|
||||
var dataClass:Class = cls("net.pixvi.myr.element.battle.BattleData");
|
||||
panelClass["battleData"] = new dataClass();
|
||||
panel.battlePosition = null;
|
||||
var result:Object = null;
|
||||
var completed:Function = function(data:Object):void {
|
||||
result = {cheatNum:data.cheatNum, text:data.cheatRecords.text,
|
||||
records:data.cheatRecords.mons, master:data.cheatRecords.master};
|
||||
};
|
||||
panel.onWinCallBack = completed; panel.onLoseCallBack = completed;
|
||||
panel["battleCompleteHandler"]();
|
||||
return result;
|
||||
}
|
||||
private function finish(result:Object):void {
|
||||
if (finished) return; finished = true;
|
||||
var s:FileStream = new FileStream(); s.open(output,FileMode.WRITE);
|
||||
s.writeUTFBytes(JSON.stringify(result)); s.close();
|
||||
NativeApplication.nativeApplication.exit(result.ok ? 0 : 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
REFLECT = r'''
|
||||
var masterClass:Class = cls("net.pixvi.myr.element.master.MasterVo");
|
||||
var master:Object = new masterClass();
|
||||
cls("net.pixvi.myr.center.Game")["getIns"]()["master"] = master; master["init"]();
|
||||
finish({ok:true, master:describeType(master).toXMLString(),
|
||||
history:describeType(master.history).toXMLString(),
|
||||
activity:describeType(master.activityHistory).toXMLString()});
|
||||
'''
|
||||
|
||||
CHECK = r'''
|
||||
var outcomes:Array = [];
|
||||
var game:Object = cls("net.pixvi.myr.center.Game")["getIns"]();
|
||||
initializeFramework();
|
||||
var panel:Object = cls("net.pixvi.myr.panel.battle.BattlePanel")["getIns"]();
|
||||
var positionClass:Class = cls("net.pixvi.myr.element.battle.BattlePosition");
|
||||
for each (var test:Object in request.cases) {
|
||||
var before:String = JSON.stringify(test.snapshot);
|
||||
var previous:Object = game.master;
|
||||
var position:Object = new positionClass(); panel.battlePosition = position;
|
||||
var outcome:Object = {name:test.name};
|
||||
try {
|
||||
var roster:Object = SnapshotBridge.build(domain,test.snapshot,test.teamName);
|
||||
var nativeTeam:Object = cls("net.pixvi.myr.center.TeamCenter")["getIns"]()["getBattleTeamVo"](test.teamName);
|
||||
var units:Array = [];
|
||||
var loadedIds:Array = [];
|
||||
for each (var mon:Object in roster.master.monsters) {
|
||||
loadedIds.push(mon.id);
|
||||
if (roster.validation.selectedIds.indexOf(mon.id) < 0) continue;
|
||||
var native:Object = cls("net.pixvi.myr.center.MonsterCenter")["getIns"]()["getBattleMonVoByMid"](mon.id);
|
||||
units.push({id:mon.id,type:mon.type,level:mon.level,tplevel:mon.tplevel,
|
||||
feel:mon.feel,skin:mon.skin,skinVo:mon.skinVo == null ? null : mon.skinVo.typeId,
|
||||
skinEntry:mon.skinVo == null ? null : {monType:mon.skinVo.table().monType,
|
||||
ability:mon.skinVo.ability,
|
||||
sameOriginalEntry:mon.skinVo.table() === table["skin_info"][String(mon.skin)]},
|
||||
entangle:mon.entangle,entangleLevel:mon.entangleLevel,entangleSkill:mon.entangleSkill,
|
||||
potential:mon.potential_atk.val,skill_1:mon.skill_1,skill_2:mon.skill_2,
|
||||
atk:mon.atk,def:mon.def,hp:mon.hp,dex:mon.dex,equip1:mon.equip1,equip2:mon.equip2,
|
||||
additions:mon.abilityAdd.getRecord(),special:{atkPoi:native.atkPoi,
|
||||
atkPoiType:native.atkPoiType,crit:native.crit,thorns:native.thorns},
|
||||
battle:{atk:native.atk,def:native.def,hp:native.hpMax,dex:native.dex}});
|
||||
}
|
||||
var inventory:Array = [];
|
||||
for each (var item:Object in roster.master.bag.items) {
|
||||
var itemRecord:Object = {id:item.id,type:item.type,num:item.num};
|
||||
if ("isUsed" in item) {
|
||||
itemRecord.isUsed = item.isUsed; itemRecord.atk = item.atk.val;
|
||||
itemRecord.hp = item.hp.val; itemRecord.atkPoiType = item.atkPoiType;
|
||||
}
|
||||
inventory.push(itemRecord);
|
||||
}
|
||||
var members:Array = [];
|
||||
for each (native in nativeTeam.mons) members.push({mid:native.mid,teamPos:native.teamPos});
|
||||
outcome.ok = true; outcome.validation = roster.validation;
|
||||
outcome.contextUnchanged = panel.battlePosition === position;
|
||||
outcome.installed = game.master === roster.master;
|
||||
outcome.selectedSlots = roster.selectedTeam.monsters;
|
||||
outcome.nativeAP = nativeTeam.ap; outcome.nativeMembers = members;
|
||||
outcome.apFromRawLevel = cls("net.pixvi.myr.GameMath")["apByLevel"](test.snapshot.master.level);
|
||||
outcome.units = units; outcome.inventory = inventory;
|
||||
outcome.loadedMonsterIds = loadedIds;
|
||||
outcome.history = {monLib:roster.master.history.monLib,
|
||||
guide_record:roster.master.history.guide_record,unlockStage:roster.master.history.unlockStage,
|
||||
passStage:roster.master.history.passStage,unlockCity:roster.master.history.unlockCity};
|
||||
if (test.integrity === true) outcome.integrity = integrity(roster);
|
||||
} catch (error:Error) {
|
||||
outcome.ok = false; outcome.error = error.getStackTrace() || error.toString();
|
||||
outcome.previousMasterRestored = game.master === previous;
|
||||
}
|
||||
outcome.inputUnchanged = before == JSON.stringify(test.snapshot);
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
finish({ok:true,cases:outcomes});
|
||||
'''
|
||||
|
||||
|
||||
def synthetic_snapshot(*, rich: bool = False) -> dict:
|
||||
"""Explicit fake-account INPUTS; all derived stats remain in original AS3."""
|
||||
tables = json.loads((LOCAL / "original/tables.json").read_text(encoding="utf-8"))
|
||||
monster_table = tables["monster_info"].get("datas", tables["monster_info"])
|
||||
fields = ("atk", "def", "hp", "dex", "crit", "atkSpd", "atkVim", "selfCure", "deadBoom",
|
||||
"atkStun", "defStun", "atkPoi", "atkPoiDmg", "apCostSave", "skillCooldown",
|
||||
"sunFire", "moonHeal", "thorns")
|
||||
monsters, attributes = [], []
|
||||
for i in range(3):
|
||||
type_id = 1003010 if rich and i == 1 else 1001010
|
||||
row = monster_table[str(type_id)]
|
||||
monsters.append(dict(id=100000001 + i, typeId=type_id, level=1 + i, exp=0,
|
||||
tpLevel=0, tpExp=0, feel=0, upStar=0, process=3, mode=2,
|
||||
gAtk=row["atk_grow_min"], gDef=row["def_grow_min"],
|
||||
gHp=row["hp_grow_min"], gDex=row["dex_grow_min"],
|
||||
lock=0, sysLock=0, nicName="", timeGet=0, timeStart=0, roomId=0,
|
||||
inExploreTeam=0, equip1=0, equip2=0, equip3=0, equip4=0, equip5=0,
|
||||
pAtk=0, pDef=0, pHp=0, pDex=0, potentialLevel=1, giftTime=0,
|
||||
skin=0, entangle=0, entangleLevel=0, entangleSkills=None))
|
||||
attributes.append(dict(monsterId=100000001 + i, **dict.fromkeys(fields, 0)))
|
||||
items = []
|
||||
if rich:
|
||||
monsters[0].update(equip2=100000101, pAtk=1, pDef=2, pHp=3, pDex=1)
|
||||
monsters[1].update(skin=1003011, entangle=1, entangleLevel=1,
|
||||
entangleSkills='{"1":1001}')
|
||||
# Aggregate supplied attributes are authoritative, exactly as the server
|
||||
# snapshot represents them. Do not recalculate equipment/skin bonuses.
|
||||
attributes[0].update(hp=50, dex=3, atkPoi=2, atkPoiDmg=3)
|
||||
attributes[1].update({"atk": 13, "def": 15, "atkVim": 2})
|
||||
params = dict.fromkeys(fields, 0)
|
||||
params.update(hp=50, dex=3, atkPoi=2, atkPoiDmg=3, atkPoiType=1)
|
||||
items = [dict(id=100000101, typeId=50001, num=1, isUsed=1, itemClass=3,
|
||||
equipParams=json.dumps(params))]
|
||||
return dict(
|
||||
master=dict(id=1, level=30, roleName="Offline fixture", farmName="", avatar=0,
|
||||
createTime=0, exp=0, money=0, ti=0, ke=0, timeTi=0,
|
||||
globalAtk=2 if rich else 0, globalDef=1 if rich else 0,
|
||||
globalHp=5 if rich else 0, globalDex=1 if rich else 0),
|
||||
monsters=monsters, monsterAttributes=attributes, items=items,
|
||||
teams=[dict(teamName="teamA", teamType="battleTeam",
|
||||
monsters=[100000003, 0, 100000001, 100000002, 0, 0, 0])],
|
||||
history=dict(numAddMoney=0, numFeedMonsters={}, numKillMonsters={}, numChicken=0,
|
||||
countBattle=0, historyGacha={}, passAchi=[], passTask={}, unlockTask={},
|
||||
loopTask={}, guide_main="", guide_record=["firstOut"], unlockCity=[1],
|
||||
unlockStage={"0101": [1]}, passStage={"0101": [1]},
|
||||
monLib=[1001010, 1003010], equipLib=["50001"], payTypeCount={},
|
||||
everyDayBuyProductNum={}),
|
||||
data2=dict(unlockSkins=[1003011], timeEggItems=[]),
|
||||
activityHistory=dict(dailyGift=dict(dailyGiftCheckTime=0, dailyGiftLevel=1,
|
||||
dailyGiftCount=0, signCount=0),
|
||||
vipInfo=dict(vipTime=0, getTime=0)))
|
||||
|
||||
|
||||
def dependencies_available() -> bool:
|
||||
return (os.name == "nt" and shutil.which("java") is not None
|
||||
and (LOCAL / "air_sdk/lib/mxmlc-cli.jar").is_file()
|
||||
and (LOCAL / "original/main.library.swf").is_file())
|
||||
|
||||
|
||||
def run_harness(request: dict, *, action: str = REFLECT) -> dict:
|
||||
# Match the existing probe's reviewed, pinned dependencies, without prepare(),
|
||||
# network acquisition, account caches, or writes into another owner's build.
|
||||
from tools.battle_runtime.trusted import LIBRARY_FILES, SDK_FILES, verify_files
|
||||
|
||||
for root, pins in ((LOCAL / "air_sdk", SDK_FILES), (LOCAL / "original", LIBRARY_FILES)):
|
||||
errors = verify_files(root, pins)
|
||||
if errors:
|
||||
raise RuntimeError(f"Untrusted local snapshot-check dependencies: {errors}")
|
||||
build = LOCAL / "snapshot_bridge_checks" / uuid.uuid4().hex
|
||||
build.mkdir(parents=True)
|
||||
(build / "SnapshotBridgeCheck.as").write_text(HARNESS.replace("__ACTION__", action), encoding="utf-8")
|
||||
(build / "compiler-config.xml").write_text("<flex-config/>", encoding="utf-8")
|
||||
sdk = LOCAL / "air_sdk"
|
||||
command = [shutil.which("java") or "java", "-Duser.language=en", "-Duser.country=US", "-jar",
|
||||
str(sdk / "lib/mxmlc-cli.jar"), "-load-config=" + str(build / "compiler-config.xml"),
|
||||
"-compiler.external-library-path=" + str(sdk / "frameworks/libs/air/airglobal.swc"),
|
||||
"-compiler.library-path=" + str(sdk / "frameworks/libs/core.swc"),
|
||||
"-compiler.source-path=" + str(SOURCE), "-swf-version=50", "-debug=true",
|
||||
"-default-frame-rate=50", "-output=" + str(build / "SnapshotBridgeCheck.swf"),
|
||||
str(build / "SnapshotBridgeCheck.as")]
|
||||
compiler = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8",
|
||||
errors="replace", timeout=60, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
evidence = {"compiler_exit_code": compiler.returncode, "compiler_stdout": compiler.stdout,
|
||||
"compiler_stderr": compiler.stderr,
|
||||
"source_sha256": hashlib.sha256((SOURCE / "SnapshotBridge.as").read_bytes()).hexdigest()
|
||||
if (SOURCE / "SnapshotBridge.as").is_file() else None}
|
||||
if compiler.returncode:
|
||||
raise RuntimeError("Snapshot bridge compilation failed: " + compiler.stdout + compiler.stderr)
|
||||
(build / "check-app.xml").write_text('''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<application xmlns="http://ns.adobe.com/air/application/51.1">
|
||||
<id>local.snapshotbridge.c''' + uuid.uuid4().hex + '''</id><versionNumber>0.0.1</versionNumber>
|
||||
<filename>SnapshotBridgeCheck</filename><initialWindow><content>SnapshotBridgeCheck.swf</content>
|
||||
<visible>false</visible><systemChrome>none</systemChrome><renderMode>cpu</renderMode>
|
||||
</initialWindow><supportedProfiles>extendedDesktop</supportedProfiles></application>''', encoding="utf-8")
|
||||
(build / "request.json").write_text(json.dumps(request), encoding="utf-8")
|
||||
command = [str(sdk / "bin/adl64.exe"), "-runtime", str(sdk / "runtimes/air/win64"), "-nodebug",
|
||||
"-profile", "extendedDesktop", str(build / "check-app.xml"), "--", str(LOCAL / "original"),
|
||||
str(build / "request.json"), str(build / "result.json")]
|
||||
runtime = subprocess.run(command, cwd=build, capture_output=True, timeout=45,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
result_path = build / "result.json"
|
||||
evidence.update(process_exit_code=runtime.returncode,
|
||||
result=json.loads(result_path.read_text(encoding="utf-8")) if result_path.exists() else None,
|
||||
directory=str(build))
|
||||
(build / "evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")
|
||||
if evidence["result"] is None:
|
||||
raise RuntimeError(f"AIR snapshot check produced no result (exit {runtime.returncode})")
|
||||
return evidence
|
||||
|
||||
|
||||
def run_checks(cases: list[dict] | None = None) -> dict:
|
||||
if cases is None:
|
||||
cases = [dict(name=name, snapshot=synthetic_snapshot(rich=rich),
|
||||
teamName="teamA", integrity=True)
|
||||
for name, rich in (("plain", False), ("equipment_skin_entangle", True))]
|
||||
empty = synthetic_snapshot()
|
||||
empty["monsterAttributes"] = []
|
||||
cases.append(dict(name="empty_attributes", snapshot=empty, teamName="teamA", integrity=True))
|
||||
return run_harness({"cases": cases}, action=CHECK)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
sys.path.insert(0, str(ROOT))
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--reflect", action="store_true")
|
||||
args = parser.parse_args()
|
||||
evidence = run_harness({}) if args.reflect else run_checks()
|
||||
print(json.dumps(evidence, indent=2))
|
||||
sys.exit(0 if evidence["result"].get("ok") and
|
||||
all(c["ok"] for c in evidence["result"].get("cases", [])) else 1)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Prepare library-only copies without changing any original AVM2 code bytes."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
import hashlib
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
|
||||
def digest(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def unpack_swf(data: bytes) -> bytes:
|
||||
if len(data) < 13 or data[:3] not in (b"FWS", b"CWS"):
|
||||
raise ValueError("Expected FWS/CWS SWF")
|
||||
result = data if data[:3] == b"FWS" else b"FWS" + data[3:8] + zlib.decompress(data[8:])
|
||||
if len(result) != struct.unpack_from("<I", result, 4)[0]:
|
||||
raise ValueError("SWF declared length mismatch")
|
||||
return result
|
||||
|
||||
|
||||
def tags(data: bytes):
|
||||
start = 8 + (5 + 4 * (data[8] >> 3) + 7) // 8 + 4
|
||||
position = start
|
||||
while position < len(data):
|
||||
if position + 2 > len(data):
|
||||
raise ValueError("Truncated SWF tag")
|
||||
header = struct.unpack_from("<H", data, position)[0]
|
||||
code, size = header >> 6, header & 63
|
||||
position += 2
|
||||
if size == 63:
|
||||
if position + 4 > len(data):
|
||||
raise ValueError("Truncated long SWF tag")
|
||||
size = struct.unpack_from("<I", data, position)[0]
|
||||
position += 4
|
||||
if position + size > len(data):
|
||||
raise ValueError("Truncated SWF tag payload")
|
||||
yield code, data[position:position + size]
|
||||
position += size
|
||||
if code == 0:
|
||||
if size != 0 or position != len(data):
|
||||
raise ValueError("Invalid SWF end tag")
|
||||
return
|
||||
raise ValueError("Missing SWF end tag")
|
||||
|
||||
|
||||
def encode_tag(code: int, data: bytes) -> bytes:
|
||||
size = len(data)
|
||||
return (struct.pack("<H", (code << 6) | min(size, 63))
|
||||
+ (struct.pack("<I", size) if size >= 63 else b"") + data)
|
||||
|
||||
|
||||
def symbols(data: bytes) -> list[tuple[int, bytes]]:
|
||||
if len(data) < 2:
|
||||
raise ValueError("Truncated SymbolClass tag")
|
||||
count = struct.unpack_from("<H", data)[0]
|
||||
position, result = 2, []
|
||||
for _ in range(count):
|
||||
if position + 3 > len(data):
|
||||
raise ValueError("Truncated SymbolClass entry")
|
||||
symbol_id = struct.unpack_from("<H", data, position)[0]
|
||||
end = data.index(0, position + 2)
|
||||
result.append((symbol_id, data[position + 2:end]))
|
||||
position = end + 1
|
||||
if position != len(data):
|
||||
raise ValueError("Trailing SymbolClass bytes")
|
||||
return result
|
||||
|
||||
|
||||
def library_only(original: bytes) -> tuple[bytes, dict]:
|
||||
"""Drop document bindings, make DoABC lazy, reject executable timelines.
|
||||
|
||||
DoABC's flags/name are SWF metadata, outside the ABC payload. All ABC bytes
|
||||
(including checks, methods, skills, callbacks and static initializers) remain
|
||||
identical and ordered. Lazy loading prevents unrelated script initializers
|
||||
from running just because a library was loaded.
|
||||
"""
|
||||
raw = unpack_swf(original)
|
||||
start = 8 + (5 + 4 * (raw[8] >> 3) + 7) // 8 + 4
|
||||
output = bytearray(raw[:start])
|
||||
roots, code_hashes, lazy_changed = [], [], 0
|
||||
counts = Counter()
|
||||
for code, payload in tags(raw):
|
||||
counts[code] += 1
|
||||
if code in (12, 59, 72, 57, 71):
|
||||
raise ValueError(f"Unsupported executable/import SWF tag {code}")
|
||||
if code == 76:
|
||||
entries = symbols(payload)
|
||||
roots.extend(name.decode("utf-8") for sid, name in entries if sid == 0)
|
||||
entries = [(sid, name) for sid, name in entries if sid != 0]
|
||||
payload = struct.pack("<H", len(entries)) + b"".join(
|
||||
struct.pack("<H", sid) + name + b"\0" for sid, name in entries)
|
||||
elif code == 82:
|
||||
if len(payload) < 6:
|
||||
raise ValueError("Truncated DoABC")
|
||||
end = payload.index(0, 4)
|
||||
code_hashes.append(digest(payload[end + 1:]))
|
||||
flags = struct.unpack_from("<I", payload)[0]
|
||||
if flags not in (0, 1):
|
||||
raise ValueError("Unknown DoABC flags")
|
||||
lazy_changed += flags == 0
|
||||
payload = struct.pack("<I", 1) + payload[4:]
|
||||
output.extend(encode_tag(code, payload))
|
||||
struct.pack_into("<I", output, 4, len(output))
|
||||
result = bytes(output)
|
||||
return result, {"original_sha256": digest(original), "library_sha256": digest(result),
|
||||
"removed_document_classes": roots, "abc_sha256": code_hashes,
|
||||
"abc_count": len(code_hashes), "lazy_flags_changed": lazy_changed,
|
||||
"tag_counts": dict(counts), "abc_bytes_preserved": True}
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Reviewed identities, never extended by an imported runtime manifest.
|
||||
|
||||
SDK bytes were acquired from the official Wipro AIR SDK 51.5.1.1 distribution.
|
||||
The original libraries are deterministic library-only transforms of APK 1.9.68.
|
||||
These hashes bind execution to those bytes; they are not vendor signatures or
|
||||
proof of complete gameplay fidelity.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
SDK_FILES = {
|
||||
"bin/adl64.exe": "e22cc43b97d15ed8794f2a4eb838976413945d8e066ac0ada82fe48d1cd38069",
|
||||
"runtimes/air/win64/Adobe AIR/Versions/1.0/Adobe AIR.dll": "181d076176f76b8060c7bcaa5e9a98909b86e25b03bd994036f841614c668041",
|
||||
"lib/mxmlc-cli.jar": "fceb2e3fe9493b37f6df88d7ea3ed2644e3f19bc8a12ec78338674be17704a1a",
|
||||
"lib/compiler.jar": "5c858003d2f5711924e3a3a842f59283cbe627b6a815d6e5209da4ba0be3d03f",
|
||||
"lib/antlr.jar": "4febf283a01fa7a895ce3b91f9f2d1dd1f4d223d8ed8b799c13aaa7aaf502aec",
|
||||
"lib/guava-r08.jar": "d54f64a15314d87c811d845692c790a11ef4aaabd2c5f12de50ba634cddaf971",
|
||||
"lib/aglj40.jar": "d2339b8a1992cc934072c9fa676b33b92e1c2734267ba0745ba6e0660dd44022",
|
||||
"lib/afe.jar": "8b27d1457846380187fecd9d0e28e7d3a409fb2f761fbefe61eb93bc496c27b3",
|
||||
"lib/commons-io-2.0.1.jar": "2a3f5a206480863aae9dff03f53c930c3add6912f8785498d59442c7ebb98c5c",
|
||||
"lib/commons-cli-1.2.jar": "e7cd8951956d349b568b7ccfd4f5b2529a8c113e67c32b028f52ffda371259d9",
|
||||
"lib/lzma-sdk-9.2.jar": "ba9ae4079c05b6132f8445d0b5d9bf9564191d47393977dc29c3d083d8c6b6e6",
|
||||
"lib/rideau.jar": "ca16f52610cca6da007a71df514d403fab6757720b0a24f94e40a39aa6ee2bd3",
|
||||
"frameworks/libs/air/airglobal.swc": "e0f81fdb2029d2bb16e6987c8d85d4eba5eedfa3a23ed6e7f780bf6eb67b0546",
|
||||
"frameworks/libs/core.swc": "193bc3a54aae57424def160d1cd6f62b73d06e028d785f125ef35a91a0af4e8a",
|
||||
}
|
||||
LIBRARY_FILES = {
|
||||
"framework.library.swf": "680e9055da1ec1916af0f2526ba53e73c8e5e299c4f2b5d2061a8903c71133c1",
|
||||
"main.library.swf": "a53afc2fceb6e9592291d4e579b31fdc54f2edd827cbe6adab6b89ee5adc7b40",
|
||||
"baseui.library.swf": "31879090afb49f821646e8b8e36b1469ee9df9e1c57d3f020245e4e780360c29",
|
||||
"mainui.library.swf": "315be2c5bc2b7be0644ef16b9a0ae3c22478a8f98957d83a4361f497de7bf3f2",
|
||||
"mainui2.library.swf": "a544277d3d308178f669289da13f02ae3403f9ddd46a730f21885d0c8be4e766",
|
||||
"mainui3.library.swf": "e2f1977cfbf5acaa09b1bdec281954eb32a56c3d2340f09ffe6526dbb6094c58",
|
||||
"movieclip.library.swf": "3e7967c4dff48c64e61b6c2cfeaa4dd49e279ea644096e948bcd1926f9a4dc8d",
|
||||
}
|
||||
TABLE_FILES = {
|
||||
"setting":"68bb8d2ee882a1c14b98315eb61dfb3545dc633173b53409b1dec3af68fb7af3",
|
||||
"game_setting":"8810981688414e3cef520976911d16e2847df0a435dccd792e2dd527695283e3",
|
||||
"monster_info":"081747ddc5b7afba03f69e65f5eba6af815b9fbd3ea7e0821c7f8807d9486921",
|
||||
"monster_skill":"0fea0eb8553a4868ff704210e9adfd09c6e2b2c3b2730e9ebe25642fa478bf9b",
|
||||
"monster_setting":"49388d221e3d4461fede3b176526d593ec0f1647a8b93a8d2b33a712761febab",
|
||||
"monster_level":"1e435fb320b66c19152216e16159ad04c677e8dc970f32534e50b59363b71340",
|
||||
"team_info":"21254655b6966ab67d5b3f1105568ab6ed13e2eecc4f05d27ef016de0e34ced2",
|
||||
"stage_info":"47ccef41d460f4ef23732624cf302e863a22ca33148dc02629841d764c38b487",
|
||||
"task_info":"b833985c54e11f3079a3ccc53709f87d25b1f8301699b3eb99613a826a469744",
|
||||
"item_info":"9beeab37d107b09d02c4491a052594390c874c92328f524752080f5a7fab21e2",
|
||||
"potential_info":"cf43bde8204ed1e13c555cfc48df5a54ea7f2df7813e017a04ba02f0453d7895",
|
||||
"entangle_info":"9be02321151385379b0992053a41f2df6e911d6e3a9474701c118faad386e8b0",
|
||||
"skin_info":"80841c945544b8b6db87c480ca194cf59c9e7da18718cea66585328d4d18edd2",
|
||||
"upstar_info":"b53db40bd0c94e0c0fff7e6c1bc5519b05c0aa353f4ba384cd3062ad5865c350",
|
||||
}
|
||||
|
||||
|
||||
def verify_files(root: Path, expected: dict[str, str]) -> list[dict]:
|
||||
reasons = []
|
||||
for name, sha in expected.items():
|
||||
path = root / name
|
||||
if not path.is_file():
|
||||
reasons.append({"code": "dependency_missing", "detail": name})
|
||||
else:
|
||||
with path.open("rb") as stream:
|
||||
actual = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if actual != sha:
|
||||
reasons.append({"code": "dependency_digest_mismatch", "detail": name})
|
||||
return reasons
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Opt-in offline native validation; full evidence stays in ignored local_state.
|
||||
|
||||
The default runs canonical original configs in all three contexts with fake
|
||||
account INPUTS. --request accepts a data-only BattleRequest JSON file. This tool
|
||||
never imports a runner command, downloads dependencies, or calls game services.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
|
||||
from ranch_assistant.battle_runtime import BattleRuntime, CONTEXTS
|
||||
from tools.battle_runtime.inputs import original_source
|
||||
from tools.battle_runtime.probe import LOCAL
|
||||
|
||||
|
||||
def summarize(result: dict) -> dict:
|
||||
scene=result.get("offline_result",{})
|
||||
battle=scene.get("battle_data",{})
|
||||
native=result.get("evidence",{}).get("result",{})
|
||||
elapsed=scene.get("wall_ms",0)
|
||||
return {"status":result["status"],"outcome":result.get("outcome"),
|
||||
"terminal_reason":scene.get("terminal_reason"),"cheatNum":battle.get("cheatNum"),
|
||||
"original_player_checks":len(scene.get("anomaly_records",{}).get("mons",[])),
|
||||
"original_unit_records":len(scene.get("original_unit_records",[])),
|
||||
"battle_left_ms":battle.get("leftTime"),"scene_wall_ms":elapsed,
|
||||
"scene_observed_fps":scene.get("observed_frames",0)*1000/elapsed if elapsed else None,
|
||||
"assets":result.get("evidence",{}).get("resource_audit"),
|
||||
"error_phase":native.get("error",{}).get("phase") if native.get("error") else None,
|
||||
"refusal_codes":[reason["code"] for reason in result.get("reasons",[])],
|
||||
"settlement_eligible":result.get("settlement_eligible",False)}
|
||||
|
||||
|
||||
def synthetic_request(context: str, *, rich=False) -> dict:
|
||||
from tools.battle_runtime.snapshot_bridge_check import synthetic_snapshot
|
||||
tables,_=original_source()
|
||||
position={"battleType":"stage","stageId":"0101","stageLevel":"1","taskTypeId":None,"taskStep":0}
|
||||
battle=tables["stage_info"]["0101"]["level"]["1"]["battle"]
|
||||
request={"context":context,"roster":synthetic_snapshot(rich=rich),"team":"teamA",
|
||||
"battle_position":position,"stage_id":"0101","difficulty":1}
|
||||
if context != "ordinary_stage":
|
||||
task_id,step=("2002014",2) if context=="task_battle" else ("1001004",0)
|
||||
request.update(stage_id=None,task_id="offline-synthetic-instance",step_index=step)
|
||||
position.update(battleType="task",stageId=None,stageLevel=None,taskTypeId=task_id,taskStep=step)
|
||||
if context=="task_battle":battle=tables["task_info"][task_id]["steps"][step]["battle"]
|
||||
request["original_data"]={"battle":battle}
|
||||
return request
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--request",type=Path)
|
||||
parser.add_argument("--contexts",choices=sorted(CONTEXTS),nargs="*",default=sorted(CONTEXTS))
|
||||
parser.add_argument("--rich",action="store_true",help="Synthetic original equipment/skin/global/addition inputs")
|
||||
parser.add_argument("--concurrent",action="store_true",help="Also verify two simultaneous component processes/storage/nonces")
|
||||
parser.add_argument("--timeout",type=float,help="Optional explicit deadline for each run")
|
||||
args=parser.parse_args()
|
||||
directory=LOCAL/"validations"/uuid.uuid4().hex
|
||||
directory.mkdir(parents=True)
|
||||
runtime=BattleRuntime();summaries=[];success=True
|
||||
if args.request is not None:
|
||||
if args.request.stat().st_size > 4*1024*1024:raise ValueError("Request exceeds 4 MiB")
|
||||
requests=[json.loads(args.request.read_text(encoding="utf-8"))]
|
||||
else:
|
||||
requests=[synthetic_request(context,rich=args.rich) for context in args.contexts]
|
||||
for index,request in enumerate(requests):
|
||||
result=runtime.run(request,timeout=args.timeout)
|
||||
(directory/f"run-{index}.local.json").write_text(json.dumps(result,ensure_ascii=True,allow_nan=False,indent=2),encoding="utf-8")
|
||||
summary={"context":request.get("context"),**summarize(result)}
|
||||
summaries.append(summary);print(json.dumps(summary),flush=True)
|
||||
success=success and result["status"]=="completed"
|
||||
if args.concurrent:
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results=list(pool.map(lambda _:runtime.probe_original_components(timeout=args.timeout or 100),range(2)))
|
||||
(directory/"concurrent.local.json").write_text(json.dumps(results,indent=2),encoding="utf-8")
|
||||
native=[result.get("evidence",{}).get("result",{}) for result in results]
|
||||
isolated=all(result["status"]=="completed" for result in results) and all(
|
||||
all(result.get(field) for result in native) and len({result[field] for result in native})==2
|
||||
for field in ("application_id","storage_directory","nonce"))
|
||||
summary={"concurrent_isolation_verified":isolated,"statuses":[result["status"] for result in results]}
|
||||
summaries.append(summary);print(json.dumps(summary),flush=True);success=success and isolated
|
||||
(directory/"summary.json").write_text(json.dumps(summaries,indent=2),encoding="utf-8")
|
||||
raise SystemExit(0 if success else 1)
|
||||
|
||||
|
||||
if __name__=="__main__":
|
||||
main()
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Fixed native runner entrypoint, invoked only in an isolated offline process."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tools.battle_runtime.probe import LOCAL, execute_probe
|
||||
from tools.battle_runtime.trusted import SDK_FILES, verify_files
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--action", choices=("scene", "components"), required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--nonce", required=True)
|
||||
parser.add_argument("--input",type=Path)
|
||||
parser.add_argument("--timeout",type=float,default=690.0)
|
||||
args = parser.parse_args()
|
||||
# No executable, command, Python import, environment, or plugin-manifest
|
||||
# options exist. Verify the code-bearing SDK before starting Java or ADL.
|
||||
reasons = verify_files(LOCAL / "air_sdk", SDK_FILES)
|
||||
if reasons:
|
||||
raise RuntimeError("AIR dependency validation failed: " + json.dumps(reasons))
|
||||
source_request = None
|
||||
if args.input is not None:
|
||||
if args.input.stat().st_size > 4*1024*1024: raise ValueError("Oversized original request")
|
||||
source_request = json.loads(args.input.read_text(encoding="utf-8"))
|
||||
evidence = execute_probe(scene=args.action == "scene",source_request=source_request,timeout=args.timeout)
|
||||
payload = {"schema": 1, "nonce": args.nonce, "evidence": evidence}
|
||||
args.output.write_text(json.dumps(payload, ensure_ascii=True, allow_nan=False), encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user