Protocol research
Recover message layouts and turn client behavior into an explicit server contract.
SOLO DEVELOPMENT · GAME PRESERVATION
I’m Tea._.Master. I build the backend, client integrations, and release systems for an archived multiplayer game.
My Hero Academia: The Strongest Hero
One developer, from protocol to production.
Server implementation · Lua mods · Deployment tooling
A place for the game this engineering makes possible.
Use a high-resolution screenshot of your character in Musutafu. Keep the environment and main HUD visible, close menus and pop-ups, and avoid cropped UI. A confirmed cooperative scene with two players would make an even stronger project image.
SOURCE SNAPSHOT 7562b5530 OCT 2026Inspect the evidence
01 / THE PROJECT
The original client needs a backend that understands its protocol, preserves its players, and responds correctly through a game session.
I own the engineering across those boundaries: investigating client behavior, building the service, integrating changes, and maintaining the release path.
Recover message layouts and turn client behavior into an explicit server contract.
Implement sessions, world routing, progression, rankings, and mode-specific state.
Deliver Lua fixes and content changes through a signed update channel.
Maintain deployment, backup, operator, and community web tools.
Sole developer describes the engineering work presented here. The wider community contributes testing, server ownership, and community operations.
02 / SYSTEM ARCHITECTURE
A modular Python runtime connects wire transport, mode orchestration, and player persistence. The supervisor controls release activation outside the game child. These are explicit logical boundaries within the deployed service.
Supplies the server list and the game endpoint.
Each client establishes an independent gameplay session.
Protocol codec → handlers → account and world state.
Participant endpoints receive mode-specific frame, wave, and lifecycle broadcasts.
Separate JSON stores preserve state. The supervisor stages and checks runtime updates.
HTTP bootstrap returns the server configuration. The client then opens a separate binary TCP session, decoded by the protocol codec and routed to game handlers.
bootstrap.py
protocol.py · game_server.pyA run tracks participant endpoints and its lifecycle. Mode-specific updates are broadcast back to connected participants. Each mode still needs its own entry, combat, and settlement behavior.
joint_operation_runtime.py
game_server.pyProfiles and rankings use separate file stores with process locks and snapshot tooling. The supervisor replaces the child inside the existing session; the storage remains container-local.
profile_store.py · store_lock.py
gameye_update_supervisor.pyReceipt replay, deferred nested saves, and rollback belong to the persistence layer.
INSPECT THE TRANSACTION CLIENT TRUSTA signed publication contract.Publisher metadata and Android verification bind the delivered bytes to a known version.
INSPECT THE UPDATE PIPELINE RELEASE CONTROLCode activation outside the child.Staging, snapshots, health checks, and prior-code recovery are owned by the supervisor.
INSPECT THE SUPERVISORLogical subsystems, not a claim of separate microservices. Highlighting shows the selected flow. Shared Joint Operation transport is experimental and explicitly opt-in.
Signed Lua content and the community website run as companion services. Gameye’s account portal uses loopback port 18083; its supervisor uses 18082.
03 / ENGINEERING IN PRACTICE
Different constraints. Concrete implementation decisions. Each case connects the problem to the code that addresses it.
A connection is only the beginning. A wrong field width, message ID, or callback layout can still break the archived client.
A schema registry maps recovered message names and IDs to typed layouts. A shared codec handles numbers, strings, repeated fields, and payloads before handing messages to gameplay code.
A consistent encoding boundary for server handlers, with explicit protocol limits instead of ad hoc field handling.
schema.py→protocol.py
Scope: packet compatibility supports implementation; individual game modes still require their own lifecycle logic.
A synchronous save could traverse and serialize unrelated accounts while running on the shared event loop.
I narrowed affected paths to account-scoped saves, moved mail persistence onto that path, and removed per-save account deep copies in favor of cached serialized payloads. Save-stage timing makes remaining expensive work visible.
Less unrelated work in the affected save paths, with a smaller persistence scope for an individual account update.
Account update → full-store work
Changed account → targeted persistence
save_account(urs)profile_store.py
Verification: source changes are traceable in commits aa07418, b467946, and 7d09ac1. A controlled latency benchmark is not included in this case study.
Replacing a Gameye session can change the public addresses packaged into the client. An ordinary code release should not need a new session allocation.
A supervisor validates and stages source bundles, waits for child shutdown and save completion, snapshots local data, then starts the new runtime. A failed health check restores the prior code.
Routine source updates preserve the session and its allocated addresses, with a controlled recovery path for failed starts.
gameye_update_supervisor.py
Operational boundary: players disconnect during a child restart. Session replacement and incompatible data changes still need a separate migration procedure.
04 / IMPLEMENTATION
Lightweight server services.
A separate client and web layer.
HTTP bootstrap, binary TCP, sessions, and gameplay systems.
Signed script updates and packaging for bootstrap or asset changes.
Static exports, Cloudflare Pages Functions, and operator interfaces.
Runtime packaging, controlled releases, and regression coverage.
05 / ORIGINAL SYSTEMS WORK
These examples show the boundaries that matter: protecting a player’s state, delivering trusted client code, and changing the running service with a recovery path.
Inventory, mode state, and the replay receipt cross one strict account-save boundary.
def apply_assessment_transaction(
self, urs: str, receipt_key: str, mutate: Callable[[], dict]
) -> tuple[dict, bool]:
"""Commit inventory and Assessment state in the same account replacement.
A receipt survives process restarts. In-memory changes roll back if a
strict account write fails; nested inventory saves are deferred.
"""
account, key = str(urs), str(receipt_key)
if not account.strip() or not key.strip():
raise ValueError("Assessment transaction requires account and receipt")
with self._lock:
existing = self.assessment_state.get(account, {}).get("receipts", {}).get(key)
if existing is not None:
return copy.deepcopy(existing), False
if self.path is not None and self.read_only:
raise PermissionError("Profile store is read-only")
if self._deferred_account_saves:
raise RuntimeError("Nested Assessment transactions are not supported")
snapshot = self._snapshot_peacekeeping_account(account)
try:
self._deferred_account_saves += 1
try:
result = mutate()
if not isinstance(result, dict):
raise TypeError("Assessment receipt must be a dictionary")
state = self.assessment_state.setdefault(account, {})
state.setdefault("receipts", {})[key] = copy.deepcopy(result)
json.dumps(state, allow_nan=False)
finally:
self._deferred_account_saves -= 1
self.save(force=True, only_account=account, strict=True)
except BaseException:
self._restore_peacekeeping_account(account, snapshot)
raise
return copy.deepcopy(result), True7562b55src/mhatsh_server/profile_store.pyMatches local implementationThis is an account-local transaction boundary. It does not claim a distributed transaction across all members of a party.
test_assessment_inventory_receipt_survives_restart_and_duplicatetest_strict_fsync_failure_rolls_back_inventory_permit_and_receipttest_partial_multiplayer_commit_retry_cannot_reverse_frozen_outcomeLocal focused checks are separate from full-suite results and live-device validation. The evidence manifest records the validation scope.
A versioned Lua payload is bound to its channel, hash, size, URL, and bootstrap policy before publication.
def publish(args: argparse.Namespace) -> dict[str, object]:
if not VERSION_RE.fullmatch(args.version):
raise ValueError("Version may contain only letters, numbers, dot, underscore and hyphen")
if args.min_bootstrap < 1:
raise ValueError("Minimum bootstrap version must be positive")
source = args.source.read_bytes()
if not source.strip():
raise ValueError("Mod source is empty")
digest = hashlib.sha256(source).hexdigest()
filename = f"mod-{args.version}.lua"
base_url = args.base_url.rstrip("/")
manifest: dict[str, object] = {
"schema": 1,
"channel": args.channel,
"version": args.version,
"file": filename,
"sha256": digest,
"size": len(source),
"url": f"{base_url}/api/client-mod/{args.channel}/{filename}",
"minBootstrap": args.min_bootstrap,
"enabled": not args.disabled,
}
private = serialization.load_pem_private_key(args.key.read_bytes(), password=None)
signature = private.sign(canonical(manifest), padding.PKCS1v15(), hashes.SHA256())
manifest["signature"] = base64.b64encode(signature).decode("ascii")
directory = args.output / args.channel
directory.mkdir(parents=True, exist_ok=True)
target = directory / filename
temporary = directory / (filename + ".tmp")
temporary.write_bytes(source)
os.replace(temporary, target)
manifest_tmp = directory / "manifest.json.tmp"
manifest_tmp.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
os.replace(manifest_tmp, directory / "manifest.json")
return manifest7562b55scripts/publish_client_mod.pyMatches local implementationPython publication and Java verification implement the same signed-manifest contract. Routine Lua updates use this path; bootstrap, native-code, and packaged-asset changes still require APK work.
The consumer verifies the signature with its public key, then checks downloaded bytes against the signed hash and size.
String canonical="MHA-TSH-MOD-V1\n"+channel+'\n'+version+'\n'+filename+'\n'+expectedHash+'\n'+expectedSize+'\n'+url+'\n'+minimum+'\n'+(enabled?"1":"0")+'\n';
Signature verifier=Signature.getInstance("SHA256withRSA");
byte[] keyBytes=android.util.Base64.decode(MOD_PUBLIC_KEY,android.util.Base64.DEFAULT);
PublicKey key=KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(keyBytes));
verifier.initVerify(key); verifier.update(canonical.getBytes("UTF-8"));
if(!verifier.verify(android.util.Base64.decode(manifest.getString("signature"),android.util.Base64.DEFAULT)))
throw new SecurityException("Invalid client-mod manifest signature");
File directory=new File(context.getFilesDir(),"client_mod");
if(!directory.exists()&&!directory.mkdirs()) throw new IOException("Cannot create client-mod directory");
if(!enabled) { android.util.Log.i("ClientModUpdate","Remote updates disabled by signed manifest"); return; }
File current=new File(directory,"current.lua");
if(current.isFile()&¤t.length()==expectedSize&&expectedHash.equals(sha256(current))) {
writeText(new File(directory,"version.txt"),version+"\n");
android.util.Log.i("ClientModUpdate","Verified cached signed client mod "+version+" sha256="+expectedHash);
return;
}
byte[] payload=download(url,MOD_MAX_BYTES);
if(payload.length!=expectedSize||!expectedHash.equals(sha256(payload)))
throw new SecurityException("Downloaded client-mod hash or size mismatch");client_tools/obb_importer/PatchUpdateActivity.java
test_published_test_channel_is_signed_and_matches_payloadtest_only_manifest_referenced_payload_can_be_servedtest_payload_restores_crlf_expansion_only_when_signed_hash_matchesLocal focused checks are separate from full-suite results and live-device validation. The evidence manifest records the validation scope.
The supervisor controls child shutdown, local data snapshots, staged startup, and health-based code rollback.
def activate(release, commit, sequence):
previous = {k: state[k] for k in ("release", "commit")}
try:
state.update(sequence=sequence, phase="saving")
save()
stop()
backup_dir = Path("/app/backups/gameye-deploy")
backup_dir.mkdir(parents=True, exist_ok=True)
backup = backup_dir / (str(sequence) + ".tar.gz")
with tarfile.open(backup, "w:gz") as archive:
for name in ("data", "secrets"):
for path in (Path("/app") / name).rglob("*"):
if path.is_file() and not path.is_symlink() and root not in path.parents and not path.name.endswith((".lock", ".tmp")):
archive.add(path, arcname=str(path.relative_to("/app")), recursive=False)
state.update(release=release, commit=commit, phase="starting", backup=str(backup))
save()
start(release)
if not healthy():
stop()
state.update(previous)
start(previous["release"])
state["phase"] = "rolled_back" if healthy() else "failed"
else:
state["phase"] = "healthy"
# Keep the active/previous code and three local save snapshots.
try:
for candidate in releases.iterdir():
if str(candidate) not in {release, previous["release"]} and candidate.resolve().parent == releases.resolve() and not candidate.is_symlink():
shutil.rmtree(candidate)
backups = sorted(backup_dir.glob("*.tar.gz"), key=lambda p: int(p.name.split(".")[0]), reverse=True)
for old_backup in backups[3:]:
old_backup.unlink()
except OSError:
print("Deployment healthy; old-file cleanup needs attention", flush=True)
save()
print("Gameye deployment", sequence, state["phase"], state["commit"], flush=True)
except Exception as exc:
if child is None or child.poll() is not None:
state.update(previous)
start(previous["release"])
healthy()
state["phase"] = "failed"
save()
print("Gameye deployment failed:", type(exc).__name__, flush=True)
finally:
lock.release()7562b55scripts/gameye_update_supervisor.pyMatches local implementationThis provides code rollback within the same session. It does not automatically reverse incompatible data migrations; storage remains container-local. No new live deployment was performed for this case study.
Behavior reviewed in source. A new supervisor process or deployment was not started.
Local focused checks are separate from full-suite results and live-device validation. The evidence manifest records the validation scope.
Every displayed function is extracted from committed source at 7562b55 and matches the current local implementation. Select a design decision to highlight its lines.
DEVELOPMENT HISTORY
5e771179323871aa6d61aaa07418Snapshot: 7562b5586c1095988c426efdaf912e2eea02b927 · 30 October 2026.
Counts from the committed source snapshot. Protocol entries are unique Name values in analysis/protocol_ids.csv; backend modules are tracked .py files under src/mhatsh_server; test modules are tracked Tests/test_*.py files, including descendants. Counts establish repository footprint, not implemented-message coverage, authored client assets, or passing tests.
The transaction and client-update check run passed 11 tests locally. A broader run that included experimental Joint Operation transport produced 26 passes and five failures: its test server stub lacks a daily-progress refresh method. That mode remains explicitly opt-in and requires device validation. No complete-suite pass, uptime percentage, concurrency benchmark, or live rollout is claimed.
ENGINEERED FOR A COMMUNITY
Explore the game, its community, and the work around it.