TICKET-388. Byte-identical copy of Tools/YGOLegacy/probe-feature-messages.py; the Unity copy stays until Phase 2. Run from the Unity repo root: python contract/probe-feature-messages.py --dll out/win64/ygol-engine.dll. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DJUFwdiGCHipsxLkgxssSR
2529 lines
130 KiB
Python
2529 lines
130 KiB
Python
#!/usr/bin/env python3
|
|
# probe-feature-messages.py -- the gate for ygoserver patch 0006 (TICKET-170)
|
|
# until TICKET-171 gives the clients real senders.
|
|
#
|
|
# Talks the raw ygopro wire to a ygoserver lobby and checks that Capability
|
|
# (0x40), Appearance (0x41) and Dialogue (0x42) behave as the patch says:
|
|
# the server advertises its own capability between STOC_JOIN_GAME and
|
|
# STOC_TYPE_CHANGE, relays the three stamped with the SENDER'S seat, drops a
|
|
# wrong-sized or observer-sent appearance/dialogue without dropping the
|
|
# connection, and replays a seat's stored capability + appearance to a later
|
|
# joiner right after that seat's PlayerEnter; a seat that leaves or moves to
|
|
# the observers loses its stored appearance.
|
|
#
|
|
# python Tools/YGOLegacy/probe-feature-messages.py --port 7911
|
|
# against a server something else is hosting (the Editor's LAN room, a
|
|
# BotArena --host server worker). Needs an EMPTY or one-seat lobby: the
|
|
# probe takes seats.
|
|
# python Tools/YGOLegacy/probe-feature-messages.py --dll <path\to\ygoserver.dll>
|
|
# hosts its own lobby from that DLL (cwd must be the repo root, like
|
|
# BotArena: the DLL reads ./expansions and friends) on --port (default
|
|
# 7961) and stops it at the end. This is how a freshly built, not yet
|
|
# installed DLL is probed.
|
|
#
|
|
# With --dll it then gates patch 0009 (TICKET-258, setup pairs): it hosts five
|
|
# more rooms from a scratch folder holding a one-card cards.cdb and a probe
|
|
# script/special.lua, plays each to the duel start and checks that ygol.*
|
|
# tokens after slot 11 are never read as seeds, reach the registry before
|
|
# special.lua runs (Single, every duel of a Match, Tag), arrive as STOC 0x43 in
|
|
# every join snapshot (late watcher included) and ride in the replay; and that
|
|
# a host string without them behaves as before.
|
|
#
|
|
# With --dll it also gates patch 0011 (TICKET-285, host seats): the server's
|
|
# capability says protocol 2 + flag 0x8; the host's seat plan (0x50) comes back
|
|
# to everyone as a 25-byte STOC 0x50 stamped 0xFF with no token on the wire; a
|
|
# non-host plan is ignored; a plain join / ToDuelist skips a Cpu seat; a claim
|
|
# (0x51 before JoinGame) gets exactly its seat or JOINERROR + disconnect; a plan
|
|
# that would make a human's seat Cpu is refused to the host alone with the
|
|
# refused revision; swap (0x52) and move (0x53) use the stock lobby messages in
|
|
# the documented order and re-broadcast the plan; a late joiner gets the plan in
|
|
# its snapshot; with no plan ever sent the snapshot is as 0009 left it.
|
|
# Single and Tag.
|
|
#
|
|
# With --dll it also gates patch 0012 (TICKET-286, rules restart): the server's
|
|
# capability has flag 0x10; Prepare (0x54) is refused with a reason while a
|
|
# participant lacks 0x10, otherwise every human and watcher gets its OWN seat and
|
|
# token (0x54) and nobody else's; acks (0x55) count in the host-only status
|
|
# (0x56); Commit (0x56) only after every ack, then phase 2 to everyone; Abort and
|
|
# the 5 s ack timeout unfreeze; joins / swaps are frozen meanwhile; a replacement
|
|
# server started with ygolboot=<hex> admits only the secret's holder, which
|
|
# installs Reserved seats (plan with the restart id + deadline) and opens with
|
|
# 0x58; a Reserved seat is taken only by the matching token + restart id before
|
|
# the deadline, a restoring seat never auto-readies until SeatResume Complete
|
|
# (0x57), the deadline turns it Open, the observer token resumes a watcher, and
|
|
# ygol.room.watchers=0 refuses every other observer. Prepare after START is
|
|
# refused. Single and Tag.
|
|
#
|
|
# With --dll it also gates patch 0013 (seat state): the server's capability says
|
|
# protocol 3 + flag 0x20; a seated duelist's SEAT_STATE (0x59, 4 bytes) comes
|
|
# back to everyone stamped with its seat; an observer's, a wrong-sized one, an
|
|
# unknown version or state is dropped; a late joiner gets a seat's stored state
|
|
# right after that seat's APPEARANCE; "none" clears it; a swap re-sends it
|
|
# stamped with the new seat; leaving, moving to the watchers and the duel start
|
|
# clear it; during the duel it is dropped. Single and Tag.
|
|
#
|
|
# With --dll it also gates patch 0014 (TICKET-299, lobby after match): the
|
|
# server's capability says protocol 4 + flag 0x40; a surrender, a decided Bo3
|
|
# and a mid-duel leave each send the stock DUEL_END and then MATCH_OVER (0x5A,
|
|
# stamped 0xFF: version, seat count, occupied seats) with nobody disconnected;
|
|
# a joiner's snapshot is the lobby again (nobody READY, appearance and the seat
|
|
# plan kept, the leaver's seat empty, the game-2 seat swap undone); a CPU seat
|
|
# loads its deck without readying until SeatResume Complete with a zero id, a
|
|
# human is never held; Prepare is accepted again; a second START plays a second
|
|
# duel on the same connections with duel_count back at 0; a host leaving mid-
|
|
# duel hands the room over once the lobby is back. Single, Match and Tag.
|
|
#
|
|
# With --dll it also gates patch 0017 (TICKET-328, coin toss): the server's
|
|
# capability says protocol 5 + flag 0x80; START sends no SELECT_HAND but one
|
|
# 4-byte COIN_TOSS (0x5B: version 1, chooser seat, face, 10 s) to every seat
|
|
# and watcher, then SELECT_TP to the chooser alone (single: the winning seat,
|
|
# face == seat; tag: seat 0 or 2, face == seat / 2); a HAND_RESULT and the
|
|
# non-chooser's TP_RESULT change nothing; with no answer the duel starts ~10 s
|
|
# later with the chooser FIRST; an answer starts it at once and the timer never
|
|
# fires afterwards; game 2 of a Match sends face 0xFF with the loser as the
|
|
# chooser, same timer. Single, Match and Tag.
|
|
#
|
|
# With --dll it also gates patch 0018 (TICKET-326, spectators see all): with no
|
|
# ygol.room.spectatorview=hidden pair a watcher's MSG_DRAW and hand
|
|
# MSG_UPDATE_DATA packets are byte-identical to the card OWNER's full copy, and a
|
|
# late watcher's field snapshot carries every hand code; with the pair the
|
|
# watcher's packets are byte-identical to the OPPONENT's masked copy (code 0) and
|
|
# the snapshot's hands are zeroed. Duelists see their own codes and zeros for the
|
|
# other side in both modes. Single and Tag, each in both modes.
|
|
#
|
|
# With --dll it also gates patch 0019 (TICKET-338, deck lists): the server's
|
|
# capability says protocol 6 + flag 0x100; with 40 distinct codes per deck every
|
|
# seat gets DECK_LIST (0x5C) kind 0 for its own side only -- sorted, the
|
|
# submitted deck minus what it drew -- and never kind 1 / 2 or the other side's
|
|
# list; a watcher gets kind 1 (the real order, top first: the next draw is its
|
|
# first code) and kind 2 (the submitted Main Deck, sorted; after the Tag swap
|
|
# the partner's) for both sides when the host shows all, and nothing when
|
|
# hidden; a turn pass shrinks the lists by the drawn card; a late watcher's
|
|
# snapshot carries kinds 1 and 2 (show all) or none (hidden). Single and Tag,
|
|
# each in both modes.
|
|
#
|
|
# With --dll it also gates patch 0020 (TICKET-360, profile): the server's
|
|
# capability says protocol 7 + flag 0x200; a seated human's PROFILE (0x5D, 98
|
|
# bytes: version, reserved, avatar id 32 chars, frame id 16 chars) comes back to
|
|
# everyone stamped with its seat; an observer's, a CPU seat's, a wrong-sized one
|
|
# and an unknown version are dropped; a late joiner gets a seat's stored profile
|
|
# after that seat's APPEARANCE; a newer one replaces it; a swap re-sends it
|
|
# stamped with the new seat; it survives the 0014 lobby reset; moving to the
|
|
# watchers and leaving clear it. Single and Tag.
|
|
#
|
|
# With --dll it also gates patch 0023 (TICKET-378, attack preview): the server's
|
|
# capability says protocol 8 + flag 0x400; each side summons a Probe Knight and
|
|
# the second seat enters its Battle Phase; its ATTACK_PREVIEW ask (0x5E: version,
|
|
# count, 4 bytes per pair) is answered to that seat alone (0x5E: version, count,
|
|
# per pair the 4 bytes echoed + the engine's 24-byte answer): the knight into the
|
|
# knight says both die, a direct attack says illegal, a pair the prompt does not
|
|
# list or the engine refuses is left out; the other seat's ask, a watcher's ask,
|
|
# a wrong version, too many pairs and a wrong length are dropped without a reply;
|
|
# a seat that never asks gets no 0x5E and the duel goes on. Single and Tag.
|
|
#
|
|
# Exit 0 only when every check passed. Stock DLL: the first check fails; the
|
|
# 0011 DLL fails at the capability flags.
|
|
import argparse, base64, ctypes, lzma, os, shutil, socket, sqlite3, struct, sys, tempfile, threading, time
|
|
|
|
CTOS_CHAT, CTOS_PLAYER_INFO, CTOS_JOIN_GAME, CTOS_LEAVE_GAME = 0x16, 0x10, 0x12, 0x13
|
|
CTOS_HS_TOOBSERVER = 0x21
|
|
CTOS_CAPABILITY, CTOS_APPEARANCE, CTOS_DIALOGUE = 0x40, 0x41, 0x42
|
|
CTOS_SEAT_PLAN, CTOS_SEAT_REQUEST, CTOS_SEAT_SWAP, CTOS_SEAT_MOVE = 0x50, 0x51, 0x52, 0x53
|
|
STOC_SEAT_PLAN = 0x50
|
|
STOC_JOIN_GAME, STOC_TYPE_CHANGE, STOC_CHAT = 0x12, 0x13, 0x19
|
|
STOC_HS_PLAYER_ENTER, STOC_HS_PLAYER_CHANGE = 0x20, 0x21
|
|
STOC_CAPABILITY, STOC_APPEARANCE, STOC_DIALOGUE = 0x40, 0x41, 0x42
|
|
PRO_VERSION = 0x1362
|
|
OBSERVER, SERVER = 7, 0xFF
|
|
|
|
NAMES = {0x12: "JOIN_GAME", 0x13: "TYPE_CHANGE", 0x19: "CHAT", 0x20: "PLAYER_ENTER", 0x21: "PLAYER_CHANGE",
|
|
0x22: "WATCH_CHANGE", 0x40: "CAPABILITY", 0x41: "APPEARANCE", 0x42: "DIALOGUE", 0x15: "DUEL_START", 0x02: "ERROR_MSG",
|
|
0x50: "SEAT_PLAN", 0x59: "SEAT_STATE"}
|
|
|
|
failures = []
|
|
|
|
|
|
def check(cond, what):
|
|
print((" PASS " if cond else " FAIL ") + what)
|
|
if not cond:
|
|
failures.append(what)
|
|
return cond
|
|
|
|
|
|
def utf16(s, n):
|
|
b = s.encode("utf-16-le")[: (n - 1) * 2]
|
|
return b + b"\0" * (n * 2 - len(b))
|
|
|
|
|
|
def frame(pid, payload=b""):
|
|
return struct.pack("<HB", len(payload) + 1, pid) + payload
|
|
|
|
|
|
def capability_bytes(protocol=1, flags=3):
|
|
return struct.pack("<HI", protocol, flags)
|
|
|
|
|
|
def appearance_bytes(tag):
|
|
items = struct.pack("<8i", *[1000 + tag * 10 + i for i in range(8)])
|
|
return items + utf16("deck-%d" % tag, 48) + utf16("character-%d" % tag, 64) + utf16("group-%d" % tag, 48)
|
|
|
|
|
|
def dialogue_bytes(tag):
|
|
return struct.pack("<BBhII", 1, 1, tag, 4000 + tag, 5000 + tag) + utf16("corpus-%d" % tag, 48) + utf16("event-%d" % tag, 48)
|
|
|
|
|
|
class Client:
|
|
def __init__(self, host, port, name):
|
|
self.name = name
|
|
self.sock = socket.create_connection((host, port), timeout=5)
|
|
self.sock.setblocking(False)
|
|
self.buf = b""
|
|
self.seat = None
|
|
self.closed = False
|
|
self.log = []
|
|
|
|
def send(self, pid, payload=b""):
|
|
self.sock.sendall(frame(pid, payload))
|
|
|
|
def drain(self, quiet=0.6, limit=8.0):
|
|
out, last, start = [], time.time(), time.time()
|
|
while time.time() - last < quiet and time.time() - start < limit:
|
|
try:
|
|
chunk = self.sock.recv(65536)
|
|
if not chunk:
|
|
self.closed = True
|
|
break
|
|
self.buf += chunk
|
|
last = time.time()
|
|
except BlockingIOError:
|
|
time.sleep(0.02)
|
|
except (ConnectionResetError, ConnectionAbortedError):
|
|
self.closed = True
|
|
break
|
|
while len(self.buf) >= 3:
|
|
(ln,) = struct.unpack_from("<H", self.buf, 0)
|
|
if len(self.buf) < 2 + ln:
|
|
break
|
|
pid = self.buf[2]
|
|
out.append((pid, bytes(self.buf[3:2 + ln])))
|
|
self.buf = self.buf[2 + ln:]
|
|
return out
|
|
|
|
def join(self, claim=None):
|
|
self.send(CTOS_PLAYER_INFO, utf16(self.name, 20))
|
|
if claim is not None:
|
|
self.send(CTOS_SEAT_REQUEST, seat_request_bytes(*claim))
|
|
self.send(CTOS_JOIN_GAME, struct.pack("<HxxI", PRO_VERSION, 0) + utf16("", 20))
|
|
pkts = self.drain()
|
|
for pid, payload in pkts:
|
|
if pid == STOC_TYPE_CHANGE:
|
|
self.seat = payload[0] & 0x0F
|
|
return pkts
|
|
|
|
def close(self):
|
|
try:
|
|
self.sock.close()
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def seat_request_bytes(seat, token, restart_id=b"\0" * 16, protocol=2):
|
|
return struct.pack("<H", protocol) + restart_id + bytes([seat]) + token
|
|
|
|
|
|
def seat_plan_bytes(revision, seat_count, kinds, tokens, restart_id=b"\0" * 16, deadline_ms=0):
|
|
kinds = list(kinds) + [0] * (4 - len(kinds))
|
|
tokens = list(tokens) + [None] * (4 - len(tokens))
|
|
return restart_id + struct.pack("<IHB", deadline_ms, revision, seat_count) + bytes(kinds) + b"".join(t or b"\0" * 16 for t in tokens)
|
|
|
|
|
|
def describe(pkts):
|
|
def tail(p, d):
|
|
if p == STOC_HS_PLAYER_CHANGE and len(d) == 1:
|
|
return "(0x%02x)" % d[0]
|
|
if p == STOC_TYPE_CHANGE and len(d) == 1:
|
|
return "(0x%02x)" % d[0]
|
|
if p == STOC_HS_PLAYER_ENTER and len(d) == 41:
|
|
return "(%d)" % d[40]
|
|
if p in (0x40, 0x41, 0x42, 0x19, 0x50) and len(d) >= 2:
|
|
return "(%d)" % struct.unpack_from("<H", d, 0)[0]
|
|
return ""
|
|
return ", ".join(NAMES.get(p, "0x%02x" % p) + tail(p, d) for p, d in pkts)
|
|
|
|
|
|
def stamped(pkts, pid, seat):
|
|
return [d[2:] for p, d in pkts if p == pid and len(d) >= 2 and struct.unpack_from("<H", d, 0)[0] == seat]
|
|
|
|
|
|
def check_snapshot(who, pkts, expect_seat_appearance, forbid_seat):
|
|
ids = [p for p, _ in pkts]
|
|
ok = STOC_JOIN_GAME in ids and STOC_TYPE_CHANGE in ids
|
|
check(ok, "%s: join answered with JOIN_GAME + TYPE_CHANGE" % who)
|
|
if not ok:
|
|
return
|
|
j, t = ids.index(STOC_JOIN_GAME), ids.index(STOC_TYPE_CHANGE)
|
|
server_caps = [(i, d) for i, (p, d) in enumerate(pkts) if p == STOC_CAPABILITY and struct.unpack_from("<H", d, 0)[0] == SERVER]
|
|
check(len(server_caps) == 1 and j < server_caps[0][0] < t, "%s: the server's CAPABILITY(0xFF) sits between JOIN_GAME and TYPE_CHANGE" % who)
|
|
if server_caps:
|
|
proto, flags = struct.unpack_from("<HI", server_caps[0][1], 2)
|
|
check(proto == 8 and flags == 0x7FF, "%s: server capability is protocol 8, flags 0x7FF (appearance | dialogue | setup pairs | seat plan | rules restart | seat state | lobby after match | coin toss | deck lists | profile | attack preview), got %d / 0x%x" % (who, proto, flags))
|
|
for seat, expected in expect_seat_appearance.items():
|
|
enters = [i for i, (p, d) in enumerate(pkts) if p == STOC_HS_PLAYER_ENTER and d[40] == seat]
|
|
apps = [i for i, (p, d) in enumerate(pkts) if p == STOC_APPEARANCE and struct.unpack_from("<H", d, 0)[0] == seat]
|
|
check(len(enters) == 1 and len(apps) == 1 and apps[0] > enters[0], "%s: seat %d's stored APPEARANCE replays after its PLAYER_ENTER" % (who, seat))
|
|
check(bool(apps) and pkts[apps[0]][1][2:] == expected, "%s: the replayed appearance for seat %d is byte-identical to what that seat sent" % (who, seat))
|
|
caps = [i for i, (p, d) in enumerate(pkts) if p == STOC_CAPABILITY and struct.unpack_from("<H", d, 0)[0] == seat]
|
|
check(len(caps) == 1 and caps[0] > enters[0], "%s: seat %d's stored CAPABILITY replays after its PLAYER_ENTER" % (who, seat))
|
|
for seat in forbid_seat:
|
|
check(not stamped(pkts, STOC_APPEARANCE, seat), "%s: no APPEARANCE for seat %d (it left / moved to the observers)" % (who, seat))
|
|
|
|
|
|
_dlls = {}
|
|
|
|
|
|
def host_dll(path, port, mode=0, tail=""):
|
|
path = os.path.abspath(path)
|
|
if path not in _dlls:
|
|
dll = ctypes.CDLL(path)
|
|
dll.start_server.argtypes = [ctypes.c_char_p]
|
|
dll.start_server.restype = ctypes.c_int
|
|
_dlls[path] = dll
|
|
dll = _dlls[path]
|
|
args = ("%d -1 5 %d F T F 8000 5 1 180 0 %s" % (port, mode, tail)).strip().encode()
|
|
t = threading.Thread(target=lambda: dll.start_server(args), daemon=True, name="ygoserver")
|
|
t.start()
|
|
deadline = time.time() + 20
|
|
while time.time() < deadline:
|
|
if not t.is_alive():
|
|
sys.exit("ygoserver thread ended before it listened (cwd must be the repo root; port %d free?)" % port)
|
|
try:
|
|
socket.create_connection(("127.0.0.1", port), timeout=0.3).close()
|
|
return dll, t
|
|
except OSError:
|
|
time.sleep(0.1)
|
|
sys.exit("ygoserver did not listen on %d within 20 s" % port)
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--host", default="127.0.0.1")
|
|
ap.add_argument("--port", type=int, default=None)
|
|
ap.add_argument("--dll", default=None, help="host a lobby from this ygoserver.dll instead of connecting to one")
|
|
o = ap.parse_args()
|
|
port = o.port or (7961 if o.dll else 7911)
|
|
feature_suite(o, port)
|
|
if o.dll:
|
|
setup_suite(o.dll, port + 1)
|
|
seat_suite(o.dll, port + 10)
|
|
restart_suite(o.dll, port + 20)
|
|
seat_state_suite(o.dll, port + 40)
|
|
lobby_suite(o.dll, port + 50)
|
|
coin_toss_suite(o.dll, port + 60)
|
|
spectator_suite(o.dll, port + 70)
|
|
deck_list_suite(o.dll, port + 80)
|
|
profile_suite(o.dll, port + 90)
|
|
attack_preview_suite(o.dll, port + 100)
|
|
print()
|
|
if failures:
|
|
print("FAILED: %d check(s)" % len(failures))
|
|
for f in failures:
|
|
print(" - " + f)
|
|
return 1
|
|
print("ALL CHECKS PASSED")
|
|
return 0
|
|
|
|
|
|
def feature_suite(o, port):
|
|
dll = thread = None
|
|
if o.dll:
|
|
dll, thread = host_dll(o.dll, port)
|
|
print("hosting from %s on port %d" % (o.dll, port))
|
|
|
|
print("== A joins (a duelist seat)")
|
|
a = Client(o.host, port, "probe-a")
|
|
pa = a.join()
|
|
print(" A got: " + describe(pa))
|
|
check_snapshot("A", pa, {}, [])
|
|
if not check(a.seat is not None and a.seat < 4, "A holds a duelist seat (got %r); the lobby must have a free seat" % a.seat):
|
|
return finish(dll, thread, [a])
|
|
|
|
print("== A sends Capability and Appearance: relayed to A, stamped with A's seat")
|
|
a.send(CTOS_CAPABILITY, capability_bytes())
|
|
a.send(CTOS_APPEARANCE, appearance_bytes(1))
|
|
pk = a.drain()
|
|
print(" A got: " + describe(pk))
|
|
check(stamped(pk, STOC_CAPABILITY, a.seat) == [capability_bytes()], "A: CAPABILITY relayed to the sender, stamped %d, same 6 bytes" % a.seat)
|
|
check(stamped(pk, STOC_APPEARANCE, a.seat) == [appearance_bytes(1)], "A: APPEARANCE relayed to the sender, stamped %d, same 352 bytes" % a.seat)
|
|
check(all(struct.unpack_from("<H", d, 0)[0] != SERVER for p, d in pk if p in (STOC_CAPABILITY, STOC_APPEARANCE)), "A: nothing here is stamped 0xFF (the payload cannot choose its sender)")
|
|
|
|
print("== A sends a 353-byte appearance: dropped, connection alive")
|
|
a.send(CTOS_APPEARANCE, appearance_bytes(9) + b"\0")
|
|
pk = a.drain()
|
|
check(not pk, "A: the 353-byte appearance produced nothing (%s)" % describe(pk))
|
|
a.send(CTOS_CHAT, "hi".encode("utf-16-le") + b"\0\0")
|
|
pk = a.drain()
|
|
check(any(p == STOC_CHAT for p, _ in pk), "A: a chat afterwards still echoes (connection kept)")
|
|
|
|
print("== B joins: the snapshot replays A's capability + appearance after A's PlayerEnter")
|
|
b = Client(o.host, port, "probe-b")
|
|
pb = b.join()
|
|
print(" B got: " + describe(pb))
|
|
check_snapshot("B", pb, {a.seat: appearance_bytes(1)}, [])
|
|
a.drain()
|
|
if not check(b.seat is not None and b.seat < 4, "B holds a duelist seat (got %r)" % b.seat):
|
|
return finish(dll, thread, [a, b])
|
|
|
|
print("== B sends its own Appearance: relayed to everyone, stamped with B's seat")
|
|
b.send(CTOS_APPEARANCE, appearance_bytes(2))
|
|
pka, pkb = a.drain(), b.drain()
|
|
check(stamped(pka, STOC_APPEARANCE, b.seat) == [appearance_bytes(2)], "A received B's APPEARANCE stamped %d" % b.seat)
|
|
check(stamped(pkb, STOC_APPEARANCE, b.seat) == [appearance_bytes(2)], "B received its own APPEARANCE stamped %d" % b.seat)
|
|
|
|
print("== B moves to the observers: its appearance is forgotten; observer appearance/dialogue drop, capability relays")
|
|
b.send(CTOS_HS_TOOBSERVER)
|
|
pka, pkb = a.drain(), b.drain()
|
|
check(any(p == STOC_TYPE_CHANGE and (d[0] & 0x0F) == OBSERVER for p, d in pkb), "B is now an observer (TYPE_CHANGE 7)")
|
|
b_old_seat = b.seat
|
|
b.seat = OBSERVER
|
|
b.send(CTOS_APPEARANCE, appearance_bytes(3))
|
|
b.send(CTOS_DIALOGUE, dialogue_bytes(3))
|
|
pka, pkb = a.drain(), b.drain()
|
|
check(not [1 for p, _ in pka + pkb if p in (STOC_APPEARANCE, STOC_DIALOGUE)], "observer B's APPEARANCE and DIALOGUE were dropped (A: %s | B: %s)" % (describe(pka), describe(pkb)))
|
|
b.send(CTOS_CAPABILITY, capability_bytes(1, 1))
|
|
pka, pkb = a.drain(), b.drain()
|
|
check(stamped(pka, STOC_CAPABILITY, OBSERVER) == [capability_bytes(1, 1)] and stamped(pkb, STOC_CAPABILITY, OBSERVER) == [capability_bytes(1, 1)], "observer B's CAPABILITY relayed to A and B stamped 7")
|
|
|
|
print("== A sends Dialogue: relayed live to A and observer B, stamped with A's seat")
|
|
a.send(CTOS_DIALOGUE, dialogue_bytes(4))
|
|
pka, pkb = a.drain(), b.drain()
|
|
check(stamped(pka, STOC_DIALOGUE, a.seat) == [dialogue_bytes(4)], "A received its DIALOGUE stamped %d, same 204 bytes" % a.seat)
|
|
check(stamped(pkb, STOC_DIALOGUE, a.seat) == [dialogue_bytes(4)], "observer B received A's DIALOGUE stamped %d" % a.seat)
|
|
|
|
print("== C joins into B's old seat: A's appearance replays, B's does not (cleared on ToObserver); dialogue was never stored")
|
|
c = Client(o.host, port, "probe-c")
|
|
pc = c.join()
|
|
print(" C got: " + describe(pc))
|
|
check_snapshot("C", pc, {a.seat: appearance_bytes(1)}, [b_old_seat])
|
|
check(not [1 for p, _ in pc if p == STOC_DIALOGUE], "C: no DIALOGUE in the snapshot (events are never stored)")
|
|
a.drain(); b.drain()
|
|
|
|
print("== C sends Appearance then leaves: D's snapshot no longer carries C's seat")
|
|
if check(c.seat is not None and c.seat < 4, "C holds a duelist seat (got %r)" % c.seat):
|
|
c.send(CTOS_APPEARANCE, appearance_bytes(5))
|
|
pka = a.drain(); c.drain(); b.drain()
|
|
check(stamped(pka, STOC_APPEARANCE, c.seat) == [appearance_bytes(5)], "A received C's APPEARANCE stamped %d" % c.seat)
|
|
c_seat = c.seat
|
|
c.send(CTOS_LEAVE_GAME)
|
|
c.close()
|
|
time.sleep(0.5)
|
|
a.drain(); b.drain()
|
|
d = Client(o.host, port, "probe-d")
|
|
pd = d.join()
|
|
print(" D got: " + describe(pd))
|
|
check_snapshot("D", pd, {a.seat: appearance_bytes(1)}, [c_seat])
|
|
d.close()
|
|
return finish(dll, thread, [a, b])
|
|
|
|
|
|
def finish(dll, thread, clients):
|
|
for cl in clients:
|
|
cl.close()
|
|
if dll is not None:
|
|
time.sleep(0.3)
|
|
try:
|
|
dll.stop_server()
|
|
except OSError:
|
|
pass
|
|
thread.join(5)
|
|
|
|
|
|
# --- patch 0009: setup pairs ------------------------------------------------
|
|
CTOS_UPDATE_DECK, CTOS_HAND_RESULT, CTOS_TP_RESULT, CTOS_SURRENDER, CTOS_HS_START = 0x02, 0x03, 0x04, 0x14, 0x25
|
|
STOC_SELECT_HAND, STOC_SELECT_TP, STOC_CHANGE_SIDE, STOC_REPLAY = 0x03, 0x04, 0x07, 0x17
|
|
STOC_SETUP_PAIRS = 0x43
|
|
REPLAY_COMPRESSED, REPLAY_TAG, REPLAY_YGOL_SETUP_PAIRS = 0x1, 0x2, 0x40000000
|
|
PROBE_CARD = 89631139
|
|
PROBE_KNIGHT = PROBE_CARD + 500 # patch 0023: level 4, 1800 / 1000
|
|
NAMES.update({0x03: "SELECT_HAND", 0x04: "SELECT_TP", 0x05: "HAND_RESULT", 0x07: "CHANGE_SIDE", 0x09: "DECK_COUNT",
|
|
0x17: "REPLAY", 0x01: "GAME_MSG", 0x18: "TIME_LIMIT", 0x16: "DUEL_END", 0x43: "SETUP_PAIRS"})
|
|
|
|
|
|
def deck_bytes(codes=None):
|
|
codes = list(codes) if codes is not None else [PROBE_CARD] * 40
|
|
return struct.pack("<II", len(codes), 0) + struct.pack("<%dI" % len(codes), *codes)
|
|
|
|
|
|
def seed_token(tag):
|
|
return base64.b64encode(struct.pack("<8I", *[tag * 100 + i for i in range(8)])).decode()
|
|
|
|
|
|
def pairs_block(pairs):
|
|
out = struct.pack("<H", len(pairs))
|
|
for p in pairs:
|
|
out += struct.pack("<H", len(p)) + p.encode()
|
|
return out
|
|
|
|
|
|
def read_pairs_block(b):
|
|
(n,) = struct.unpack_from("<H", b, 0)
|
|
off, out = 2, []
|
|
for _ in range(n):
|
|
(ln,) = struct.unpack_from("<H", b, off)
|
|
out.append(b[off + 2:off + 2 + ln].decode())
|
|
off += 2 + ln
|
|
return out, off
|
|
|
|
|
|
def make_workspace():
|
|
root = tempfile.mkdtemp(prefix="ygol-probe-0009-")
|
|
os.makedirs(os.path.join(root, "script"))
|
|
os.makedirs(os.path.join(root, "Data"))
|
|
# without utility.lua the engine fail-fasts (0xC0000409) at the duel start
|
|
repo = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
shutil.copy(os.path.join(repo, "Data", "script.zip"), os.path.join(root, "Data", "script.zip"))
|
|
db = sqlite3.connect(os.path.join(root, "cards.cdb"))
|
|
db.execute("CREATE TABLE datas(id integer primary key, ot integer, alias integer, setcode integer, type integer, atk integer, def integer, level integer, race integer, attribute integer, category integer)")
|
|
db.execute("CREATE TABLE texts(id integer primary key, name text, desc text" + "".join(", str%d text" % i for i in range(1, 17)) + ")")
|
|
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 17, 3000, 2500, 8, 8192, 16, 0)", (PROBE_CARD,))
|
|
db.execute("INSERT INTO texts VALUES(?, 'Probe Dragon', ''" + ", ''" * 16 + ")", (PROBE_CARD,))
|
|
# patch 0019: four decks of 40 DISTINCT codes, so a sorted list and a real order can be told apart
|
|
for code in (c for deck in DECK_LIST_CODES for c in deck):
|
|
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 17, 3000, 2500, 8, 8192, 16, 0)", (code,))
|
|
db.execute("INSERT INTO texts VALUES(?, 'Probe Dragon %d', ''" % (code - PROBE_CARD) + ", ''" * 16 + ")", (code,))
|
|
# patch 0023: a level-4 normal monster, so a seat can summon without a tribute and attack with it
|
|
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 17, 1800, 1000, 4, 1, 16, 0)", (PROBE_KNIGHT,))
|
|
db.execute("INSERT INTO texts VALUES(?, 'Probe Knight', ''" + ", ''" * 16 + ")", (PROBE_KNIGHT,))
|
|
db.commit()
|
|
db.close()
|
|
return root
|
|
|
|
|
|
def write_special(root, pairs):
|
|
want = {}
|
|
for p in pairs:
|
|
k, v = p.split("=", 1)
|
|
want[k] = v
|
|
entries = ", ".join('["%s"] = [==[%s]==]' % (k, v) for k, v in want.items())
|
|
lua = """local want = { %s }
|
|
local got, bad = 0, nil
|
|
for k, v in pairs(Duel.GetRegistry()) do
|
|
if string.sub(k, 1, 5) == "ygol." then
|
|
got = got + 1
|
|
if want[k] ~= v then bad = k end
|
|
end
|
|
end
|
|
local n = 0
|
|
for _ in pairs(want) do n = n + 1 end
|
|
local verdict = bad and ("BAD " .. bad) or (got == n and "OK" or "COUNT")
|
|
error("YGOLPROBE " .. verdict .. " " .. got .. "/" .. n .. " mode=" .. tostring(Duel.GetRegistryValue("duel_mode")) .. " count=" .. tostring(Duel.GetRegistryValue("duel_count")), 0)
|
|
""" % entries
|
|
with open(os.path.join(root, "script", "special.lua"), "w", newline="\n") as f:
|
|
f.write(lua)
|
|
|
|
|
|
def pump(clients, until, limit=10.0, hand=None, tp=b"\x01", chain=False):
|
|
# hand / tp None: the prompt is logged and left unanswered (patch 0017: SELECT_HAND never comes, the server times SELECT_TP)
|
|
deadline = time.time() + limit
|
|
while time.time() < deadline:
|
|
for c in clients:
|
|
for pid, d in c.drain(quiet=0.05, limit=0.3):
|
|
c.log.append((pid, d))
|
|
if pid == STOC_SELECT_HAND and hand is not None:
|
|
c.send(CTOS_HAND_RESULT, bytes([hand(c)]))
|
|
elif pid == STOC_SELECT_TP and tp is not None:
|
|
c.send(CTOS_TP_RESULT, tp)
|
|
elif pid == STOC_CHANGE_SIDE:
|
|
c.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
elif chain and pid == 0x01 and d and d[0] == MSG_SELECT_CHAIN:
|
|
c.send(CTOS_TIME_CONFIRM)
|
|
c.send(CTOS_RESPONSE, struct.pack("<i", -1)) # patch 0019 suite: no chain, so the turn can pass
|
|
if until():
|
|
return True
|
|
return until()
|
|
|
|
|
|
def probe_lines(c):
|
|
out = []
|
|
for p, d in c.log:
|
|
if p == STOC_CHAT and len(d) > 2:
|
|
text = d[2:].decode("utf-16-le", "replace").split("\0")[0]
|
|
if "YGOLPROBE" in text:
|
|
out.append(text[text.index("YGOLPROBE"):])
|
|
return out
|
|
|
|
|
|
def replays(c):
|
|
out = []
|
|
for p, d in c.log:
|
|
if p != STOC_REPLAY or len(d) < 80:
|
|
continue
|
|
flag, datasize = struct.unpack_from("<I", d, 8)[0], struct.unpack_from("<I", d, 16)[0]
|
|
seeds = list(struct.unpack_from("<8I", d, 32))
|
|
body = d[80:]
|
|
if flag & REPLAY_COMPRESSED:
|
|
filt = lzma._decode_filter_properties(lzma.FILTER_LZMA1, d[24:29])
|
|
body = lzma.LZMADecompressor(lzma.FORMAT_RAW, filters=[filt]).decompress(body, max_length=datasize)
|
|
out.append((flag, seeds, body))
|
|
return out
|
|
|
|
|
|
def check_snapshot_pairs(who, pkts, pairs):
|
|
ids = [p for p, _ in pkts]
|
|
got = [d for p, d in pkts if p == STOC_SETUP_PAIRS]
|
|
if not pairs:
|
|
check(not got, "%s: no SETUP_PAIRS in the snapshot when the host string has none" % who)
|
|
return
|
|
if not check(len(got) == 1, "%s: exactly one SETUP_PAIRS in the snapshot (%s)" % (who, describe(pkts))):
|
|
return
|
|
i = ids.index(STOC_SETUP_PAIRS)
|
|
caps = [k for k, (p, d) in enumerate(pkts) if p == STOC_CAPABILITY and struct.unpack_from("<H", d, 0)[0] == SERVER]
|
|
t = ids.index(STOC_TYPE_CHANGE) if STOC_TYPE_CHANGE in ids else -1
|
|
check(bool(caps) and caps[0] < i < t, "%s: SETUP_PAIRS sits after the server's CAPABILITY and before TYPE_CHANGE" % who)
|
|
sender = struct.unpack_from("<H", got[0], 0)[0]
|
|
decoded, size = read_pairs_block(got[0][2:])
|
|
check(sender == SERVER, "%s: SETUP_PAIRS is stamped 0xFF (server), got 0x%x" % (who, sender))
|
|
check(decoded == pairs and size == len(got[0]) - 2, "%s: SETUP_PAIRS carries the %d pairs in host-string order, nothing else" % (who, len(pairs)))
|
|
|
|
|
|
def check_replay(who, c, pairs, seed_tag, tag=False):
|
|
reps = replays(c)
|
|
if not check(len(reps) >= 1, "%s: a REPLAY arrived at duel end" % who):
|
|
return
|
|
flag, seeds, body = reps[-1]
|
|
if pairs:
|
|
if not check(flag & REPLAY_YGOL_SETUP_PAIRS, "%s: replay flag has the setup pairs bit 0x40000000 (flag 0x%x)" % (who, flag)):
|
|
return
|
|
(blen,) = struct.unpack_from("<I", body, 0)
|
|
decoded, size = read_pairs_block(body[4:4 + blen])
|
|
check(decoded == pairs and size == blen, "%s: replay body starts with uint32 length %d + the pairs block, in order" % (who, blen))
|
|
names_at = 4 + blen
|
|
else:
|
|
check(not flag & REPLAY_YGOL_SETUP_PAIRS, "%s: replay flag has NO setup pairs bit (flag 0x%x)" % (who, flag))
|
|
names_at = 0
|
|
name = body[names_at:names_at + 40].decode("utf-16-le", "replace").split("\0")[0]
|
|
check(name.startswith("pair-"), "%s: the first player name follows at offset %d (got %r)" % (who, names_at, name))
|
|
check(bool(flag & REPLAY_TAG) == tag, "%s: replay tag flag is %s" % (who, tag))
|
|
if seed_tag is not None:
|
|
want = [seed_tag * 100 + i for i in range(8)]
|
|
check(seeds == want, "%s: replay seed_sequence is the seed token from the host string (%s)" % (who, "match" if seeds == want else "got %r" % seeds[:2]))
|
|
|
|
|
|
def join_all(port, count):
|
|
out = []
|
|
for i in range(count):
|
|
c = Client("127.0.0.1", port, "pair-%d" % i)
|
|
c.log = list(c.join())
|
|
out.append(c)
|
|
for other in out[:-1]:
|
|
other.log += other.drain(quiet=0.2)
|
|
return out
|
|
|
|
|
|
def start_duel(clients, port, hand):
|
|
for c in clients:
|
|
c.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pump(clients, lambda: False, limit=0.8, hand=hand)
|
|
clients[0].send(CTOS_HS_START)
|
|
|
|
|
|
def run_case(dll_path, root, port, label, pairs, mode=0, seed_tag=None, junk=(), watcher=False):
|
|
print("== setup pairs, %s: %d pair(s), mode %d" % (label, len(pairs), mode))
|
|
write_special(root, pairs)
|
|
tokens = list(pairs[:len(pairs) // 2]) + list(junk) + list(pairs[len(pairs) // 2:])
|
|
if seed_tag is not None:
|
|
tokens.append(seed_token(seed_tag))
|
|
dll, thread = host_dll(dll_path, port, mode, " ".join(tokens))
|
|
seats = 4 if mode == 2 else 2
|
|
clients = join_all(port, seats)
|
|
for c in clients:
|
|
check_snapshot_pairs("%s seat %d" % (label, c.seat), [x for x in c.log], pairs)
|
|
hand = lambda c: 1 if c.seat == 0 else 2
|
|
start_duel(clients, port, hand)
|
|
want_verdict = "OK %d/%d" % (len(pairs), len(pairs))
|
|
mode_name = {0: "single", 1: "match", 2: "tag"}[mode]
|
|
ok = pump(clients, lambda: all(probe_lines(c) for c in clients), limit=15, hand=hand)
|
|
lines = probe_lines(clients[0])
|
|
print(" special.lua said: %s" % lines)
|
|
check(ok and lines and lines[0].startswith("YGOLPROBE " + want_verdict + " mode=" + mode_name),
|
|
"%s: special.lua saw exactly the pairs in the registry, before it ran (%s)" % (label, want_verdict))
|
|
if mode == 1:
|
|
check(bool(lines) and lines[0].endswith("count=0"), "%s: duel 1 ran with duel_count=0" % label)
|
|
everyone = list(clients)
|
|
if watcher:
|
|
w = Client("127.0.0.1", port, "pair-watch")
|
|
w.log = list(w.join())
|
|
print(" late watcher got: " + describe(w.log[:8]))
|
|
check(w.seat == OBSERVER, "%s: the mid-duel joiner is an observer" % label)
|
|
check_snapshot_pairs("%s late watcher" % label, w.log, pairs)
|
|
everyone.append(w)
|
|
surrender = clients[:2] if mode == 2 else clients[:1]
|
|
for c in surrender:
|
|
c.send(CTOS_SURRENDER)
|
|
pump(everyone, lambda: all(replays(c) for c in clients), limit=10, hand=hand)
|
|
check_replay(label, clients[0], pairs, seed_tag, tag=(mode == 2))
|
|
if watcher:
|
|
check_replay("%s late watcher" % label, everyone[-1], pairs, seed_tag)
|
|
if mode == 1:
|
|
ok = pump(clients, lambda: len(probe_lines(clients[0])) >= 2, limit=15, hand=hand)
|
|
lines = probe_lines(clients[0])
|
|
print(" special.lua, duel 2: %s" % lines[1:])
|
|
check(ok and len(lines) >= 2 and lines[1].startswith("YGOLPROBE " + want_verdict + " mode=match") and lines[1].endswith("count=1"),
|
|
"%s: duel 2 of the match also saw the pairs before special.lua (duel_count=1)" % label)
|
|
clients[0].send(CTOS_SURRENDER)
|
|
pump(clients, lambda: len(replays(clients[0])) >= 2, limit=10, hand=hand)
|
|
check(len(replays(clients[0])) >= 2, "%s: duel 2 sent its own replay" % label)
|
|
if len(replays(clients[0])) >= 2:
|
|
flag, _, body = replays(clients[0])[1]
|
|
(blen,) = struct.unpack_from("<I", body, 0)
|
|
check(flag & REPLAY_YGOL_SETUP_PAIRS and read_pairs_block(body[4:4 + blen])[0] == pairs, "%s: duel 2's replay carries the pairs too" % label)
|
|
for c in everyone:
|
|
c.close()
|
|
time.sleep(0.3)
|
|
try:
|
|
dll.stop_server()
|
|
except OSError:
|
|
pass
|
|
thread.join(5)
|
|
check(not thread.is_alive(), "%s: the server thread ended" % label)
|
|
|
|
|
|
def setup_suite(dll_path, port):
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
print()
|
|
print("hosting setup-pair rooms from %s in %s" % (dll_path, root))
|
|
try:
|
|
many = ["ygol.ruleset=rush", "ygol.scripts=rulesets/rush.lua,mutators/draw2.lua", "ygol.p.draw2.count=2",
|
|
"ygol.p.title.name=Blue%20Eyes%2C%20White"] + ["ygol.p.k%02d=v%02d" % (i, i) for i in range(16)]
|
|
run_case(dll_path, root, port, "none", [], seed_tag=1)
|
|
run_case(dll_path, root, port + 1, "one", ["ygol.ruleset=rush"], watcher=True)
|
|
run_case(dll_path, root, port + 2, "twenty", many, seed_tag=2, junk=["ygol.noequals", "ygol.=nokey"])
|
|
run_case(dll_path, root, port + 3, "match", ["ygol.ruleset=rush", "ygol.scripts=rulesets/rush.lua"], mode=1)
|
|
run_case(dll_path, root, port + 4, "tag", ["ygol.ruleset=rush", "ygol.scripts=rulesets/rush.lua"], mode=2)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
# --- patch 0011: host seats -------------------------------------------------
|
|
CTOS_HS_TODUELIST = 0x20
|
|
STOC_HS_WATCH_CHANGE = 0x22
|
|
WATCHERS = 0xFF
|
|
OBSERVE, READY, NOTREADY, LEAVE = 0x8, 0x9, 0xA, 0xB
|
|
|
|
|
|
def plans(pkts):
|
|
return [(struct.unpack_from("<H", d, 0)[0], struct.unpack_from("<H", d, 18)[0], d[20], tuple(d[21:25])) for p, d in pkts if p == STOC_SEAT_PLAN and len(d) == 25]
|
|
|
|
|
|
def changes(pkts):
|
|
return [d[0] for p, d in pkts if p == STOC_HS_PLAYER_CHANGE]
|
|
|
|
|
|
def enters(pkts):
|
|
return [(d[40], d[:40].decode("utf-16-le").split("\0")[0]) for p, d in pkts if p == STOC_HS_PLAYER_ENTER]
|
|
|
|
|
|
def types(pkts):
|
|
return [d[0] for p, d in pkts if p == STOC_TYPE_CHANGE]
|
|
|
|
|
|
def ids(pkts):
|
|
return [p for p, _ in pkts]
|
|
|
|
|
|
def drain_all(clients, quiet=0.4):
|
|
out = {}
|
|
for c in clients:
|
|
out[c] = c.drain(quiet=quiet)
|
|
c.log += out[c]
|
|
return out
|
|
|
|
|
|
def snapshot_plan(who, pkts, revision, seats, kinds):
|
|
idl = ids(pkts)
|
|
if not check(plans(pkts) == [(SERVER, revision, seats, kinds)], "%s: snapshot carries one SEAT_PLAN rev %d kinds %s (%s)" % (who, revision, kinds, describe(pkts))):
|
|
return
|
|
i = idl.index(STOC_SEAT_PLAN)
|
|
caps = [k for k, (p, d) in enumerate(pkts) if p == STOC_CAPABILITY and struct.unpack_from("<H", d, 0)[0] == SERVER]
|
|
t = idl.index(STOC_TYPE_CHANGE) if STOC_TYPE_CHANGE in idl else -1
|
|
check(bool(caps) and caps[0] < i < t, "%s: SEAT_PLAN sits after the server's CAPABILITY and before TYPE_CHANGE" % who)
|
|
|
|
|
|
def refused_claim(label, port, name, claim, why, all_clients):
|
|
x = Client("127.0.0.1", port, name)
|
|
x.log = list(x.join(claim=claim))
|
|
all_clients.append(x)
|
|
err = [d for p, d in x.log if p == 0x02]
|
|
check(bool(err) and err[0][0] == 1 and not types(x.log), "%s: a claim %s gets ERROR_MSG JOINERROR and no seat (%s)" % (label, why, describe(x.log)))
|
|
x.drain(quiet=0.3)
|
|
check(x.closed, "%s: the refused claimant (%s) was disconnected" % (label, why))
|
|
return x
|
|
|
|
|
|
def seat_room(dll_path, port, label, mode):
|
|
seats = 4 if mode == 2 else 2
|
|
print("== host seats, %s (%d seats)" % (label, seats))
|
|
dll, thread = host_dll(dll_path, port, mode)
|
|
tok1, bad = os.urandom(16), os.urandom(16)
|
|
all_clients = []
|
|
|
|
def client(name, claim=None):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join(claim=claim))
|
|
all_clients.append(c)
|
|
return c
|
|
|
|
h = client("seat-host")
|
|
check(h.seat == 0 and types(h.log) == [0x10], "%s: the host sits at seat 0 (TYPE_CHANGE 0x10)" % label)
|
|
check(not plans(h.log), "%s: no SEAT_PLAN in the first snapshot (no plan yet)" % label)
|
|
|
|
h.send(CTOS_SEAT_PLAN, seat_plan_bytes(1, seats, [0, 1], [None, tok1]))
|
|
pk = drain_all([h])[h]
|
|
check(plans(pk) == [(SERVER, 1, seats, (0, 1, 0, 0))] and all(len(d) == 25 for p, d in pk if p == STOC_SEAT_PLAN),
|
|
"%s: the host's plan (seat 1 Cpu, rev 1) comes back as a 25-byte SEAT_PLAN stamped 0xFF (%s)" % (label, describe(pk)))
|
|
for rev, payload, why in ((11, seat_plan_bytes(11, seats + 1, [0, 1], [None, tok1]), "the wrong seat_count"),
|
|
(12, seat_plan_bytes(12, seats, [0, 2], [None, tok1]), "kind 2 (Reserved is 286's)"),
|
|
(13, seat_plan_bytes(13, seats, [0, 1], [None, tok1], restart_id=b"\1" * 16), "a nonzero restart_id"),
|
|
(14, seat_plan_bytes(14, seats, [0, 1], [None, tok1], deadline_ms=5000), "a nonzero deadline")):
|
|
h.send(CTOS_SEAT_PLAN, payload)
|
|
pk = drain_all([h])[h]
|
|
check(plans(pk) == [(SERVER, rev, seats, (0, 1, 0, 0))], "%s: a plan with %s is refused: echo rev %d, kinds unchanged (%s)" % (label, why, rev, describe(pk)))
|
|
h.send(CTOS_SEAT_PLAN, seat_plan_bytes(15, seats, [0, 1], [None, tok1])[:-1])
|
|
pk = drain_all([h])[h]
|
|
check(not pk, "%s: a 90-byte plan is dropped (%s)" % (label, describe(pk)))
|
|
|
|
g = client("seat-guest")
|
|
want = OBSERVER if seats == 2 else 2
|
|
check(g.seat == want, "%s: a plain join skips the Cpu seat 1 and lands on %s (got %r)" % (label, "the watchers" if want == OBSERVER else "seat %d" % want, g.seat))
|
|
snapshot_plan(label + " guest", g.log, 1, seats, (0, 1, 0, 0))
|
|
drain_all([h])
|
|
g.send(CTOS_SEAT_PLAN, seat_plan_bytes(2, seats, [1, 1], [bad, bad]))
|
|
pk = drain_all([h, g])
|
|
check(not plans(pk[h]) and not plans(pk[g]), "%s: a non-host's plan is ignored (host: %s | guest: %s)" % (label, describe(pk[h]), describe(pk[g])))
|
|
|
|
refused_claim(label, port, "seat-bad", (1, bad), "with the wrong token", all_clients)
|
|
refused_claim(label, port, "seat-open", (0, tok1), "for an occupied Open seat", all_clients)
|
|
refused_claim(label, port, "seat-watch", (WATCHERS, tok1), "for the watchers (286's)", all_clients)
|
|
refused_claim(label, port, "seat-restart", (1, tok1, b"\1" * 16), "with a nonzero restart_id", all_clients)
|
|
pk = drain_all([h, g])
|
|
check(not enters(pk[h]) and not enters(pk[g]), "%s: nobody saw a refused claimant enter (%s)" % (label, describe(pk[h])))
|
|
b = client("seat-cpu", claim=(1, tok1))
|
|
check(b.seat == 1 and types(b.log) == [1], "%s: the right token gets exactly seat 1 (got %r)" % (label, b.seat))
|
|
snapshot_plan(label + " cpu", b.log, 1, seats, (0, 1, 0, 0))
|
|
pk = drain_all([h, g])
|
|
check(enters(pk[h]) == [(1, "seat-cpu")] and enters(pk[g]) == [(1, "seat-cpu")], "%s: the claimant's PLAYER_ENTER pos 1 reached everyone" % label)
|
|
|
|
h.send(CTOS_APPEARANCE, appearance_bytes(7))
|
|
h.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pk = drain_all([h, g, b])
|
|
check(changes(pk[g]) == [READY], "%s: the host's deck readies seat 0 (0x09 to everyone)" % label)
|
|
check(stamped(pk[b], STOC_APPEARANCE, 0) == [appearance_bytes(7)], "%s: the CPU saw the host's APPEARANCE stamped 0" % label)
|
|
|
|
h.send(CTOS_SEAT_PLAN, seat_plan_bytes(2, seats, [1, 1], [bad, tok1]))
|
|
pk = drain_all([h, g, b])
|
|
check(plans(pk[h]) == [(SERVER, 2, seats, (0, 1, 0, 0))] and not plans(pk[g]) and not plans(pk[b]),
|
|
"%s: a plan making the host's own seat Cpu is refused: host-only echo rev 2, kinds unchanged (host: %s | guest: %s)" % (label, describe(pk[h]), describe(pk[g])))
|
|
if seats == 4:
|
|
h.send(CTOS_SEAT_PLAN, seat_plan_bytes(3, seats, [0, 1, 1, 0], [None, tok1, bad, None]))
|
|
pk = drain_all([h, g, b])
|
|
check(plans(pk[h]) == [(SERVER, 3, seats, (0, 1, 0, 0))] and not plans(pk[g]), "%s: a plan making the guest's seat 2 Cpu is refused the same way" % label)
|
|
h.send(CTOS_SEAT_MOVE, bytes([1, WATCHERS]))
|
|
pk = drain_all([h, g, b])
|
|
check(not changes(pk[h]) and not types(pk[b]), "%s: the host cannot move the CPU to the watchers (%s)" % (label, describe(pk[h])))
|
|
|
|
h.send(CTOS_SEAT_SWAP, bytes([0, 1]))
|
|
pk = drain_all([h, g, b])
|
|
lobby = lambda pkts: [(p, d) for p, d in pkts if p in (STOC_HS_PLAYER_CHANGE, STOC_HS_PLAYER_ENTER, STOC_HS_WATCH_CHANGE, STOC_CAPABILITY, STOC_APPEARANCE, STOC_SEAT_PLAN)]
|
|
expected = [(STOC_HS_PLAYER_CHANGE, bytes([LEAVE])), (STOC_HS_PLAYER_CHANGE, bytes([0x10 | LEAVE])),
|
|
(STOC_HS_PLAYER_ENTER, utf16("seat-cpu", 20) + b"\0"), (STOC_HS_PLAYER_ENTER, utf16("seat-host", 20) + b"\1"),
|
|
(STOC_APPEARANCE, struct.pack("<H", 1) + appearance_bytes(7)),
|
|
(STOC_SEAT_PLAN, struct.pack("<H", SERVER) + b"\0" * 16 + struct.pack("<HB", 1, seats) + bytes([1, 0, 0, 0]))]
|
|
check(lobby(pk[g]) == expected, "%s: swap 0<->1 (both occupied): Leave 0, Leave 1, Enter cpu@0, Enter host@1, host's appearance stamped 1, plan rev 1 kinds Cpu/Open (%s)" % (label, describe(pk[g])))
|
|
check(lobby(pk[h]) == expected and lobby(pk[b]) == expected, "%s: the moved connections saw the same sequence" % label)
|
|
check(types(pk[h]) == [0x11] and types(pk[b]) == [0x00], "%s: TYPE_CHANGE 0x11 to the host (host bit kept) and 0x00 to the CPU, none to the guest (%s)" % (label, types(pk[g])))
|
|
tc = [k for k, (p, _) in enumerate(pk[h]) if p == STOC_TYPE_CHANGE]
|
|
en = [k for k, (p, _) in enumerate(pk[h]) if p == STOC_HS_PLAYER_ENTER]
|
|
ap = [k for k, (p, _) in enumerate(pk[h]) if p == STOC_APPEARANCE]
|
|
check(bool(tc) and en and ap and en[-1] < tc[0] < ap[0], "%s: TYPE_CHANGE sits after the Enters and before the replayed features" % label)
|
|
h.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pk = drain_all([h, g, b])
|
|
check(changes(pk[g]) == [0x10 | READY], "%s: the swap cleared READY: the host's re-sent deck readies seat 1 again (0x19)" % label)
|
|
h.send(CTOS_SEAT_SWAP, bytes([1, 1]))
|
|
h.send(CTOS_SEAT_SWAP, bytes([1, seats]))
|
|
g.send(CTOS_SEAT_SWAP, bytes([0, 1]))
|
|
pk = drain_all([h, g, b])
|
|
check(not changes(pk[h]) and not changes(pk[g]) and not types(pk[h]), "%s: swap of a seat with itself, out of range, or from a non-host does nothing" % label)
|
|
|
|
h.send(CTOS_SEAT_PLAN, seat_plan_bytes(3, seats, [0, 0], [None, None]))
|
|
pk = drain_all([h, g, b])
|
|
check(all(plans(pk[c]) == [(SERVER, 3, seats, (0, 0, 0, 0))] for c in (h, g, b)), "%s: making the occupied Cpu seat Open is accepted and broadcast (rev 3)" % label)
|
|
b.send(CTOS_LEAVE_GAME)
|
|
b.close()
|
|
time.sleep(0.4)
|
|
pk = drain_all([h, g])
|
|
check(changes(pk[g]) == [LEAVE], "%s: the CPU left seat 0 (Leave 0x0b)" % label)
|
|
|
|
h.send(CTOS_SEAT_SWAP, bytes([1, 0]))
|
|
pk = drain_all([h, g])
|
|
check(changes(pk[g]) == [0x10, NOTREADY] and not enters(pk[g]) and types(pk[h]) == [0x10],
|
|
"%s: swap with an empty seat uses MoveTo 1->0 then NotReady 0, TYPE_CHANGE 0x10 (%s)" % (label, describe(pk[g])))
|
|
check(stamped(pk[g], STOC_APPEARANCE, 0) == [appearance_bytes(7)] and plans(pk[g]) == [(SERVER, 3, seats, (0, 0, 0, 0))], "%s: appearance followed its owner to seat 0; plan echoed" % label)
|
|
h.send(CTOS_SEAT_MOVE, bytes([0, 1]))
|
|
pk = drain_all([h, g])
|
|
check(changes(pk[g]) == [0x01, 0x10 | NOTREADY] and types(pk[h]) == [0x11], "%s: own move 0->1 into an Open seat: MoveTo + NotReady, TYPE_CHANGE 0x11 (%s)" % (label, describe(pk[g])))
|
|
h.send(CTOS_SEAT_MOVE, bytes([1, 1]))
|
|
h.send(CTOS_SEAT_MOVE, bytes([1, seats]))
|
|
pk = drain_all([h, g])
|
|
check(not changes(pk[g]) and not types(pk[h]), "%s: own move onto an occupied or out-of-range seat does nothing" % label)
|
|
if seats == 4:
|
|
g.send(CTOS_SEAT_MOVE, bytes([2, WATCHERS]))
|
|
pk = drain_all([h, g])
|
|
check(changes(pk[h]) == [0x20 | OBSERVE] and types(pk[g]) == [OBSERVER], "%s: own move 2->watchers: Observe 0x28 + TYPE_CHANGE 7" % label)
|
|
g.send(CTOS_SEAT_MOVE, bytes([WATCHERS, 0]))
|
|
pk = drain_all([h, g])
|
|
check(enters(pk[h]) == [(0, "seat-guest")] and STOC_HS_WATCH_CHANGE in ids(pk[h]) and types(pk[g]) == [0], "%s: observer -> chosen seat 0: PlayerEnter, WatchChange, TYPE_CHANGE 0 (%s)" % (label, describe(pk[h])))
|
|
g.send(CTOS_SEAT_MOVE, bytes([0, WATCHERS]))
|
|
pk = drain_all([h, g])
|
|
check(changes(pk[h]) == [OBSERVE] and types(pk[g]) == [OBSERVER], "%s: own move 0->watchers: Observe 0x08 + TYPE_CHANGE 7" % label)
|
|
g.send(CTOS_SEAT_MOVE, bytes([WATCHERS, 0]))
|
|
drain_all([h, g])
|
|
g.send(CTOS_SEAT_MOVE, bytes([1, WATCHERS]))
|
|
pk = drain_all([h, g])
|
|
check(not changes(pk[h]) and not types(pk[h]), "%s: a non-host cannot move a peer to the watchers" % label)
|
|
h.send(CTOS_SEAT_MOVE, bytes([0, WATCHERS]))
|
|
pk = drain_all([h, g])
|
|
check(changes(pk[h]) == [OBSERVE] and types(pk[g]) == [OBSERVER], "%s: the host moves the peer at 0 to the watchers (Observe 0x08 + TYPE_CHANGE 7)" % label)
|
|
|
|
h.send(CTOS_SEAT_PLAN, seat_plan_bytes(4, seats, [1, 0], [tok1, None]))
|
|
pk = drain_all([h, g])
|
|
check(plans(pk[g]) == [(SERVER, 4, seats, (1, 0, 0, 0))], "%s: an empty seat 0 may become Cpu (rev 4)" % label)
|
|
g.send(CTOS_HS_TODUELIST)
|
|
pk = drain_all([h, g])
|
|
if seats == 2:
|
|
check(not types(pk[g]) and not enters(pk[h]), "%s: stock ToDuelist with only the Cpu seat free does nothing (%s)" % (label, describe(pk[h])))
|
|
else:
|
|
check(enters(pk[h]) == [(2, "seat-guest")] and types(pk[g]) == [2], "%s: stock ToDuelist skips the Cpu seat 0 and lands on 2 (%s)" % (label, describe(pk[h])))
|
|
l = client("seat-late")
|
|
check(l.seat == (OBSERVER if seats == 2 else 3), "%s: a late plain joiner skips the Cpu seat 0 (got %r)" % (label, l.seat))
|
|
snapshot_plan(label + " late joiner", l.log, 4, seats, (1, 0, 0, 0))
|
|
b2 = client("seat-cpu2", claim=(0, tok1))
|
|
check(b2.seat == 0, "%s: a claim for the re-planned Cpu seat 0 gets it (got %r)" % (label, b2.seat))
|
|
drain_all([h, g, l])
|
|
|
|
h.send(CTOS_LEAVE_GAME)
|
|
h.close()
|
|
time.sleep(0.5)
|
|
rest = [c for c in (g, l, b2)]
|
|
pk = drain_all(rest, quiet=0.6)
|
|
if seats == 4:
|
|
check(types(pk[g]) == [0x12], "%s: host left: the room goes to the human at seat 2, never the CPU at 0 (TYPE_CHANGE 0x12; got %s)" % (label, types(pk[g])))
|
|
m = client("seat-after")
|
|
check(m.seat == 1 and not plans(m.log), "%s: after the hand-over the plan is cleared: seat 1 is Open again, no SEAT_PLAN in the snapshot (seat %r, %s)" % (label, m.seat, describe(m.log)))
|
|
else:
|
|
check(all(c.closed for c in rest), "%s: host left with only a CPU seated: the room ends like an empty one (%s)" % (label, [c.closed for c in rest]))
|
|
|
|
wire = b"".join(d for c in all_clients for p, d in c.log)
|
|
check(tok1 not in wire and bad not in wire, "%s: no seat token ever appeared on the wire" % label)
|
|
for c in all_clients:
|
|
c.close()
|
|
time.sleep(0.3)
|
|
try:
|
|
dll.stop_server()
|
|
except OSError:
|
|
pass
|
|
thread.join(5)
|
|
check(not thread.is_alive(), "%s: the server thread ended" % label)
|
|
|
|
|
|
def seat_room_no_plan(dll_path, port, label, mode):
|
|
print("== host seats, %s: no plan ever sent" % label)
|
|
dll, thread = host_dll(dll_path, port, mode)
|
|
h = Client("127.0.0.1", port, "plain-host")
|
|
h.log = list(h.join())
|
|
check(ids(h.log) == [STOC_JOIN_GAME, STOC_CAPABILITY, STOC_TYPE_CHANGE, STOC_HS_PLAYER_ENTER], "%s: first snapshot is JOIN_GAME, CAPABILITY, TYPE_CHANGE, PLAYER_ENTER and nothing else (%s)" % (label, describe(h.log)))
|
|
h.send(CTOS_SEAT_SWAP, bytes([0, 1]))
|
|
pk = drain_all([h])[h]
|
|
check(changes(pk) == [0x01, 0x10 | NOTREADY] and types(pk) == [0x11] and not plans(pk), "%s: a swap into the empty seat 1 works with stock messages only, no SEAT_PLAN (%s)" % (label, describe(pk)))
|
|
g = Client("127.0.0.1", port, "plain-guest")
|
|
g.log = list(g.join())
|
|
check(g.seat == 0 and ids(g.log) == [STOC_JOIN_GAME, STOC_CAPABILITY, STOC_TYPE_CHANGE, STOC_HS_PLAYER_ENTER, STOC_HS_PLAYER_ENTER],
|
|
"%s: the guest lands on seat 0 and its snapshot has no SEAT_PLAN (%s)" % (label, describe(g.log)))
|
|
for c in (h, g):
|
|
c.close()
|
|
time.sleep(0.3)
|
|
try:
|
|
dll.stop_server()
|
|
except OSError:
|
|
pass
|
|
thread.join(5)
|
|
check(not thread.is_alive(), "%s: the server thread ended" % label)
|
|
|
|
|
|
def seat_suite(dll_path, port):
|
|
print()
|
|
print("hosting host-seat rooms from %s" % dll_path)
|
|
seat_room(dll_path, port, "single", 0)
|
|
seat_room(dll_path, port + 1, "tag", 2)
|
|
seat_room_no_plan(dll_path, port + 2, "single", 0)
|
|
seat_room_no_plan(dll_path, port + 3, "tag", 2)
|
|
|
|
|
|
# --- patch 0012: rules restart ------------------------------------------------
|
|
CTOS_RESTART_PREPARE, CTOS_RESTART_ACK, CTOS_RESTART_CONTROL, CTOS_SEAT_RESUME, CTOS_RESTART_OPEN = 0x54, 0x55, 0x56, 0x57, 0x58
|
|
STOC_ROOM_RESTARTING, STOC_RESTART_STATUS, STOC_SEAT_RESUME_RESULT, STOC_RESTART_OPEN = 0x54, 0x56, 0x57, 0x58
|
|
PREPARE, COMMIT, ABORT = 1, 2, 3
|
|
ZERO16 = b"\0" * 16
|
|
NAMES.update({0x54: "ROOM_RESTARTING", 0x56: "RESTART_STATUS", 0x57: "SEAT_RESUME_RESULT", 0x58: "RESTART_OPEN"})
|
|
|
|
|
|
def prepare_bytes(rid, timeout_ms, seat_count, seat_tokens, observer_token):
|
|
toks = list(seat_tokens) + [None] * (4 - len(seat_tokens))
|
|
return rid + struct.pack("<IB", timeout_ms, seat_count) + b"".join(t or ZERO16 for t in toks) + observer_token
|
|
|
|
|
|
def restarting(pkts):
|
|
return [(d[2], d[3:19], d[19], d[20:36], struct.unpack_from("<I", d, 36)[0]) for p, d in pkts if p == STOC_ROOM_RESTARTING and len(d) == 40]
|
|
|
|
|
|
def statuses(pkts):
|
|
return [(d[2], d[3:19], d[19], d[20], d[21], d[22]) for p, d in pkts if p == STOC_RESTART_STATUS and len(d) == 23]
|
|
|
|
|
|
def resumes(pkts):
|
|
return [(d[2:18], d[18], d[19], d[20]) for p, d in pkts if p == STOC_SEAT_RESUME_RESULT and len(d) == 21]
|
|
|
|
|
|
def opened(pkts):
|
|
return [(d[2:18], d[18]) for p, d in pkts if p == STOC_RESTART_OPEN and len(d) == 19]
|
|
|
|
|
|
def wire(pkts):
|
|
return b"".join(d for _, d in pkts)
|
|
|
|
|
|
def stop_dll(dll, thread, label):
|
|
time.sleep(0.3)
|
|
try:
|
|
dll.stop_server()
|
|
except OSError:
|
|
pass
|
|
thread.join(5)
|
|
check(not thread.is_alive(), "%s: the server thread ended" % label)
|
|
|
|
|
|
def restart_room(dll_path, port, label, mode):
|
|
seats = 4 if mode == 2 else 2
|
|
print("== rules restart, %s (%d seats): the old room" % (label, seats))
|
|
dll, thread = host_dll(dll_path, port, mode)
|
|
clients = []
|
|
|
|
def client(name, claim=None):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join(claim=claim))
|
|
clients.append(c)
|
|
return c
|
|
|
|
h = client("rs-host")
|
|
g = client("rs-guest")
|
|
w = client("rs-watch")
|
|
if w.seat != OBSERVER:
|
|
w.send(CTOS_HS_TOOBSERVER)
|
|
drain_all([h, g, w])
|
|
w.seat = OBSERVER
|
|
check(h.seat == 0 and g.seat == 1 and w.seat == OBSERVER, "%s: host at 0, guest at 1, a watcher (%r %r %r)" % (label, h.seat, g.seat, w.seat))
|
|
rid, ta, tb, tw = os.urandom(16), os.urandom(16), os.urandom(16), os.urandom(16)
|
|
prepare = prepare_bytes(rid, 30000, seats, [ta, tb], tw)
|
|
|
|
h.send(CTOS_RESTART_PREPARE, prepare)
|
|
pk = drain_all([h, g, w])
|
|
check(statuses(pk[h]) == [(PREPARE, rid, 0, 3, 0, 1)] and not restarting(pk[g]) and not restarting(pk[w]),
|
|
"%s: Prepare while a participant lacks flag 0x10 is refused to the host alone with reason 1 (%s)" % (label, describe(pk[h])))
|
|
g.send(CTOS_RESTART_PREPARE, prepare)
|
|
pk = drain_all([h, g, w])
|
|
check(not statuses(pk[g]) and not restarting(pk[h]), "%s: a non-host's Prepare is ignored" % label)
|
|
for c in (h, g, w):
|
|
c.send(CTOS_CAPABILITY, capability_bytes(2, 0x1F))
|
|
drain_all([h, g, w])
|
|
h.send(CTOS_RESTART_PREPARE, prepare_bytes(rid, 30000, seats + 1, [ta, tb], tw))
|
|
pk = drain_all([h, g, w])
|
|
check(statuses(pk[h]) == [(PREPARE, rid, 0, 3, 0, 6)], "%s: a Prepare with the wrong seat count is refused with reason 6" % label)
|
|
h.send(CTOS_RESTART_PREPARE, prepare[:-1])
|
|
pk = drain_all([h, g, w])
|
|
check(not pk[h], "%s: a 100-byte Prepare is dropped" % label)
|
|
|
|
h.send(CTOS_RESTART_PREPARE, prepare)
|
|
pk = drain_all([h, g, w])
|
|
check(restarting(pk[h]) == [(PREPARE, rid, 0, ta, 30000)], "%s: Prepare: the host gets phase 1, seat 0, its own token, 30000 ms (%s)" % (label, describe(pk[h])))
|
|
check(restarting(pk[g]) == [(PREPARE, rid, 1, tb, 30000)], "%s: the guest gets seat 1 and its own token" % label)
|
|
check(restarting(pk[w]) == [(PREPARE, rid, WATCHERS, tw, 30000)], "%s: the watcher gets seat 0xFF and the observer token" % label)
|
|
check(statuses(pk[h]) == [(PREPARE, rid, 0, 3, 0, 0)] and not statuses(pk[g]) and not statuses(pk[w]), "%s: the host alone gets the status 0/3 (%s)" % (label, statuses(pk[h])))
|
|
check(tb not in wire(pk[h]) + wire(pk[w]) and ta not in wire(pk[g]) + wire(pk[w]) and tw not in wire(pk[h]) + wire(pk[g]),
|
|
"%s: no token reached anyone but its owner" % label)
|
|
|
|
h.send(CTOS_RESTART_CONTROL, rid + bytes([COMMIT]))
|
|
pk = drain_all([h, g, w])
|
|
check(statuses(pk[h]) == [(COMMIT, rid, 0, 3, 0, 6)] and not restarting(pk[g]), "%s: Commit before the acks is refused with reason 6 and nobody is told" % label)
|
|
g.send(CTOS_RESTART_ACK, rid + bytes([PREPARE]))
|
|
pk = drain_all([h, g, w])
|
|
check(statuses(pk[h]) == [(PREPARE, rid, 1, 3, 0, 0)], "%s: the guest's ack counts: status 1/3 (%s)" % (label, statuses(pk[h])))
|
|
g.send(CTOS_RESTART_ACK, rid + bytes([PREPARE]))
|
|
g.send(CTOS_RESTART_ACK, os.urandom(16) + bytes([PREPARE]))
|
|
g.send(CTOS_RESTART_ACK, rid + bytes([COMMIT]))
|
|
pk = drain_all([h, g, w])
|
|
check(not statuses(pk[h]), "%s: a repeated, foreign or wrong-phase ack counts nothing" % label)
|
|
w.send(CTOS_RESTART_ACK, rid + bytes([PREPARE]))
|
|
h.send(CTOS_RESTART_ACK, rid + bytes([PREPARE]))
|
|
pk = drain_all([h, g, w])
|
|
check(statuses(pk[h]) == [(PREPARE, rid, 2, 3, 0, 0), (PREPARE, rid, 3, 3, 1, 0)], "%s: every Prepare ack in: status 3/3 complete (%s)" % (label, statuses(pk[h])))
|
|
|
|
x = Client("127.0.0.1", port, "rs-late")
|
|
x.log = list(x.join())
|
|
clients.append(x)
|
|
x.drain(quiet=0.3)
|
|
check([d[0] for p, d in x.log if p == 0x02] == [1] and not types(x.log) and x.closed, "%s: a join during the restart is refused (JOINERROR, disconnected)" % label)
|
|
h.send(CTOS_SEAT_SWAP, bytes([0, 1]))
|
|
h.send(CTOS_HS_START)
|
|
pk = drain_all([h, g, w])
|
|
check(not changes(pk[g]) and not types(pk[h]) and not enters(pk[g]) and 0x15 not in ids(pk[g]), "%s: swap and START are frozen during the restart (%s)" % (label, describe(pk[g])))
|
|
|
|
h.send(CTOS_RESTART_CONTROL, rid + bytes([COMMIT]))
|
|
pk = drain_all([h, g, w])
|
|
check(restarting(pk[h]) == [(COMMIT, rid, 0, ZERO16, 0)] and restarting(pk[g]) == [(COMMIT, rid, 1, ZERO16, 0)] and restarting(pk[w]) == [(COMMIT, rid, WATCHERS, ZERO16, 0)],
|
|
"%s: Commit: everyone gets phase 2 with no token" % label)
|
|
check(statuses(pk[h]) == [(COMMIT, rid, 0, 3, 0, 0)], "%s: Commit status 0/3" % label)
|
|
for c in (g, w, h):
|
|
c.send(CTOS_RESTART_ACK, rid + bytes([COMMIT]))
|
|
pk = drain_all([h, g, w])
|
|
check((statuses(pk[h]) or [None])[-1] == (COMMIT, rid, 3, 3, 1, 0), "%s: every Commit ack in: status 3/3 complete -- the host may tear down (%s)" % (label, statuses(pk[h])))
|
|
h.send(CTOS_RESTART_PREPARE, prepare)
|
|
pk = drain_all([h, g, w])
|
|
check(statuses(pk[h]) == [(PREPARE, rid, 0, 3, 0, 5)], "%s: a second Prepare while one is pending is refused with reason 5" % label)
|
|
h.send(CTOS_RESTART_CONTROL, rid + bytes([ABORT]))
|
|
pk = drain_all([h, g, w])
|
|
check(all(restarting(pk[c]) == [(ABORT, rid, c.seat if c.seat != OBSERVER else WATCHERS, ZERO16, 0)] for c in (h, g, w)), "%s: Abort: everyone gets phase 3" % label)
|
|
h.send(CTOS_SEAT_SWAP, bytes([0, 1]))
|
|
pk = drain_all([h, g, w])
|
|
check(changes(pk[w]) == [LEAVE, 0x10 | LEAVE] and len(enters(pk[w])) == 2, "%s: after Abort the room is unfrozen (swap works again)" % label)
|
|
h.send(CTOS_RESTART_PREPARE, prepare)
|
|
pk = drain_all([h, g, w])
|
|
check(statuses(pk[h]) == [(PREPARE, rid, 0, 3, 0, 0)], "%s: a new Prepare after Abort is accepted" % label)
|
|
print(" waiting 6 s for the ack timeout")
|
|
time.sleep(6.2)
|
|
pk = drain_all([h, g, w])
|
|
check(statuses(pk[h]) == [(PREPARE, rid, 0, 3, 0, 2)] and all(restarting(pk[c]) and restarting(pk[c])[-1][0] == ABORT for c in (h, g, w)),
|
|
"%s: 5 s without acks: status reason 2 to the host and phase 3 to everyone (%s)" % (label, statuses(pk[h])))
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, label + " old")
|
|
|
|
print("== rules restart, %s: the replacement server" % label)
|
|
port += 1
|
|
boot, tb2, tw2 = os.urandom(16), os.urandom(16), os.urandom(16)
|
|
dll, thread = host_dll(dll_path, port, mode, "ygolboot=" + boot.hex())
|
|
clients = []
|
|
refused_claim(label, port, "rs-plain", None, "plain join into the closed replacement server", clients)
|
|
refused_claim(label, port, "rs-badboot", (0, os.urandom(16), rid), "with the wrong bootstrap secret", clients)
|
|
refused_claim(label, port, "rs-zeroid", (0, boot, ZERO16), "with the secret but no restart id", clients)
|
|
h2 = client("rs-host2", claim=(0, boot, rid))
|
|
check(h2.seat == 0 and types(h2.log) == [0x10], "%s: the secret's holder is the host at seat 0 (got %r)" % (label, h2.seat))
|
|
refused_claim(label, port, "rs-reboot", (1, boot, rid), "re-using the one-use secret", clients)
|
|
h2.send(CTOS_SEAT_PLAN, seat_plan_bytes(1, seats, [0, 2], [None, tb2], restart_id=rid, deadline_ms=8000))
|
|
pk = drain_all([h2])[h2]
|
|
check(plans(pk) == [(SERVER, 1, seats, (0, 2, 0, 0))], "%s: the restart plan reserves seat 1 (rev 1, kinds Open/Reserved) (%s)" % (label, describe(pk)))
|
|
h2.send(CTOS_SEAT_PLAN, seat_plan_bytes(2, seats, [0, 2], [None, tb2], restart_id=os.urandom(16), deadline_ms=8000))
|
|
pk = drain_all([h2])[h2]
|
|
check(plans(pk) == [(SERVER, 2, seats, (0, 2, 0, 0))], "%s: a plan with another restart id is refused (echo rev 2, kinds unchanged)" % label)
|
|
h2.send(CTOS_SEAT_PLAN, seat_plan_bytes(3, seats, [0, 0], [None, None]))
|
|
pk = drain_all([h2])[h2]
|
|
check(plans(pk) == [(SERVER, 3, seats, (0, 2, 0, 0))], "%s: a later plan cannot open the empty Reserved seat (rev 3 accepted, seat 1 kept Reserved)" % label)
|
|
refused_claim(label, port, "rs-early", (1, tb2, rid), "before RestartOpen (still closed)", clients)
|
|
h2.send(CTOS_RESTART_OPEN, rid + tw2)
|
|
pk = drain_all([h2])[h2]
|
|
check(opened(pk) == [(rid, 1)], "%s: RestartOpen by the bootstrap host is acknowledged (%s)" % (label, describe(pk)))
|
|
h2.send(CTOS_RESTART_OPEN, rid + tw2)
|
|
pk = drain_all([h2])[h2]
|
|
check(opened(pk) == [(rid, 0)], "%s: a second RestartOpen is refused (opened 0)" % label)
|
|
|
|
c = client("rs-plain2")
|
|
check(c.seat == (OBSERVER if seats == 2 else 2), "%s: a plain join after RestartOpen skips the Reserved seat 1 (got %r)" % (label, c.seat))
|
|
snapshot_plan(label + " plain joiner", c.log, 3, seats, (0, 2, 0, 0))
|
|
refused_claim(label, port, "rs-thief", (1, os.urandom(16), rid), "for the Reserved seat with the wrong token", clients)
|
|
refused_claim(label, port, "rs-noid", (1, tb2, ZERO16), "for the Reserved seat without the restart id", clients)
|
|
refused_claim(label, port, "rs-badwatch", (WATCHERS, os.urandom(16), rid), "for the watchers with the wrong observer token", clients)
|
|
drain_all([h2, c])
|
|
g2 = client("rs-guest2", claim=(1, tb2, rid))
|
|
check(g2.seat == 1, "%s: the right token + restart id gets the Reserved seat 1 (got %r)" % (label, g2.seat))
|
|
pk = drain_all([h2, c])
|
|
check(enters(pk[h2]) == [(1, "rs-guest2")] and not plans(pk[h2]), "%s: the returning guest's PLAYER_ENTER reached the host; the seat stays Reserved until Complete" % label)
|
|
g2.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pk = drain_all([h2, g2, c])
|
|
check(not changes(pk[h2]) and not changes(pk[g2]), "%s: UpdateDeck from a restoring seat does NOT ready it (%s)" % (label, describe(pk[h2])))
|
|
g2.send(CTOS_SEAT_RESUME, os.urandom(16) + bytes([1, 0]))
|
|
pk = drain_all([h2, g2])
|
|
check(resumes(pk[g2]) and resumes(pk[g2])[0][1] == 0 and not plans(pk[h2]), "%s: SeatResume with a foreign restart id is rejected" % label)
|
|
g2.send(CTOS_SEAT_RESUME, rid + bytes([1, 0]))
|
|
pk = drain_all([h2, g2, c])
|
|
check(resumes(pk[g2]) == [(rid, 1, 1, 0)], "%s: SeatResume Complete is accepted at seat 1 (%s)" % (label, resumes(pk[g2])))
|
|
check(plans(pk[h2]) == [(SERVER, 3, seats, (0, 0, 0, 0))] and not changes(pk[h2]), "%s: Complete turns the seat Open in the broadcast plan and READY stays false (%s)" % (label, describe(pk[h2])))
|
|
g2.send(CTOS_SEAT_RESUME, rid + bytes([1, 0]))
|
|
pk = drain_all([h2, g2])
|
|
check(resumes(pk[g2]) == [(rid, 0, 1, 2)], "%s: a second Complete is rejected (reason 2)" % label)
|
|
g2.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pk = drain_all([h2, g2, c])
|
|
check(changes(pk[h2]) == [0x10 | READY], "%s: after Complete the next UpdateDeck readies seat 1 as usual (0x19)" % label)
|
|
h2.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pk = drain_all([h2, g2, c])
|
|
check(not changes(pk[g2]), "%s: the bootstrap host is restoring too: its UpdateDeck does not ready it" % label)
|
|
h2.send(CTOS_SEAT_RESUME, rid + bytes([1, 0]))
|
|
pk = drain_all([h2, g2, c])
|
|
check(resumes(pk[h2]) == [(rid, 1, 0, 0)] and not changes(pk[g2]), "%s: the host's Complete is accepted, READY still false" % label)
|
|
h2.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pk = drain_all([h2, g2, c])
|
|
check(changes(pk[g2]) == [READY], "%s: then the host's UpdateDeck readies seat 0 (0x09)" % label)
|
|
wr = client("rs-watch2", claim=(WATCHERS, tw2, rid))
|
|
check(wr.seat == OBSERVER, "%s: the observer token resumes a watcher (got %r)" % (label, wr.seat))
|
|
check(tb2 not in wire(h2.log) + wire(c.log) and tw2 not in wire(h2.log) + wire(g2.log) and boot not in wire(h2.log) + wire(g2.log) + wire(c.log),
|
|
"%s: neither the seat token, the observer token nor the bootstrap secret ever appeared on the wire" % label)
|
|
for x in clients:
|
|
x.close()
|
|
stop_dll(dll, thread, label + " replacement")
|
|
|
|
print("== rules restart, %s: the deadline opens an unclaimed seat" % label)
|
|
port += 1
|
|
boot = os.urandom(16)
|
|
dll, thread = host_dll(dll_path, port, mode, "ygolboot=" + boot.hex())
|
|
clients = []
|
|
h3 = client("rs-host3", claim=(0, boot, rid))
|
|
h3.send(CTOS_SEAT_PLAN, seat_plan_bytes(1, seats, [0, 2], [None, tb2], restart_id=rid, deadline_ms=2000))
|
|
drain_all([h3])
|
|
h3.send(CTOS_RESTART_OPEN, rid + ZERO16)
|
|
drain_all([h3])
|
|
print(" waiting 3.5 s for the deadline")
|
|
time.sleep(3.5)
|
|
pk = drain_all([h3])[h3]
|
|
check(plans(pk) == [(SERVER, 1, seats, (0, 0, 0, 0))], "%s: at the deadline the empty Reserved seat turns Open and the plan is broadcast (%s)" % (label, describe(pk)))
|
|
refused_claim(label, port, "rs-late2", (1, tb2, rid), "for an expired reservation", clients)
|
|
drain_all([h3])
|
|
l = client("rs-plainlate")
|
|
check(l.seat == 1, "%s: a plain join now takes seat 1 (got %r)" % (label, l.seat))
|
|
for x in clients:
|
|
x.close()
|
|
stop_dll(dll, thread, label + " deadline")
|
|
|
|
print("== rules restart, %s: watchers off" % label)
|
|
port += 1
|
|
dll, thread = host_dll(dll_path, port, mode, "ygol.room.watchers=0")
|
|
clients = []
|
|
h4 = client("rs-host4")
|
|
g4 = client("rs-guest4")
|
|
for i in range(seats - 2):
|
|
client("rs-fill%d" % i)
|
|
refused_claim(label, port, "rs-nowatch", None, "as an observer when watchers are off", clients)
|
|
drain_all([h4, g4])
|
|
g4.send(CTOS_HS_TOOBSERVER)
|
|
pk = drain_all([h4, g4])
|
|
check(not types(pk[g4]) and not changes(pk[h4]), "%s: HsToObserver is refused when watchers are off (%s)" % (label, describe(pk[h4])))
|
|
for x in clients:
|
|
x.close()
|
|
stop_dll(dll, thread, label + " watchers off")
|
|
|
|
|
|
def restart_after_start(dll_path, port, label):
|
|
print("== rules restart, %s: Prepare after START is refused" % label)
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, 0)
|
|
clients = join_all(port, 2)
|
|
for c in clients:
|
|
c.send(CTOS_CAPABILITY, capability_bytes(2, 0x1F))
|
|
drain_all(clients)
|
|
hand = lambda c: 1 if c.seat == 0 else 2
|
|
start_duel(clients, port, hand)
|
|
pump(clients, lambda: any(p == 0x15 for p, _ in clients[0].log), limit=5, hand=hand)
|
|
check(any(p == 0x15 for p, _ in clients[0].log), "%s: the duel started" % label)
|
|
rid = os.urandom(16)
|
|
clients[0].send(CTOS_RESTART_PREPARE, prepare_bytes(rid, 30000, 2, [os.urandom(16), os.urandom(16)], os.urandom(16)))
|
|
pk = drain_all(clients)
|
|
check(statuses(pk[clients[0]]) == [(PREPARE, rid, 0, 2, 0, 3)] and not restarting(pk[clients[1]]), "%s: Prepare after START: status reason 3, nobody told (%s)" % (label, describe(pk[clients[0]])))
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, label)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def restart_suite(dll_path, port):
|
|
print()
|
|
print("hosting rules-restart rooms from %s" % dll_path)
|
|
restart_room(dll_path, port, "single", 0)
|
|
restart_room(dll_path, port + 5, "tag", 2)
|
|
restart_after_start(dll_path, port + 10, "single")
|
|
|
|
|
|
# --- patch 0013: seat state ---------------------------------------------------
|
|
CTOS_SEAT_STATE = STOC_SEAT_STATE = 0x59
|
|
STATE_NONE, STATE_PICKING = 0, 1
|
|
|
|
|
|
def seat_state_bytes(state, version=1, value=0):
|
|
return struct.pack("<BBH", version, state, value)
|
|
|
|
|
|
def seat_states(pkts):
|
|
return [(struct.unpack_from("<H", d, 0)[0], d[2:]) for p, d in pkts if p == STOC_SEAT_STATE and len(d) == 6]
|
|
|
|
|
|
def seat_state_room(dll_path, port, label, mode):
|
|
seats = 4 if mode == 2 else 2
|
|
print("== seat state, %s (%d seats)" % (label, seats))
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, mode)
|
|
clients = []
|
|
|
|
def client(name):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join())
|
|
clients.append(c)
|
|
return c
|
|
|
|
def live():
|
|
return [c for c in clients if not c.closed]
|
|
|
|
picking, none = seat_state_bytes(STATE_PICKING), seat_state_bytes(STATE_NONE)
|
|
h = client("ss-host")
|
|
g = client("ss-guest")
|
|
w = client("ss-watch")
|
|
if w.seat != OBSERVER:
|
|
w.send(CTOS_HS_TOOBSERVER)
|
|
drain_all([h, g, w])
|
|
w.seat = OBSERVER
|
|
check(h.seat == 0 and g.seat == 1 and w.seat == OBSERVER, "%s: host at 0, guest at 1, a watcher (%r %r %r)" % (label, h.seat, g.seat, w.seat))
|
|
h.send(CTOS_APPEARANCE, appearance_bytes(13))
|
|
drain_all([h, g, w])
|
|
|
|
h.send(CTOS_SEAT_STATE, picking)
|
|
pk = drain_all([h, g, w])
|
|
check(all(seat_states(pk[c]) == [(0, picking)] for c in (h, g, w)), "%s: the host's picking-deck reaches everyone stamped 0, same 4 bytes (%s)" % (label, describe(pk[g])))
|
|
w.send(CTOS_SEAT_STATE, picking)
|
|
pk = drain_all([h, g, w])
|
|
check(not any(seat_states(pk[c]) for c in (h, g, w)), "%s: an observer's SEAT_STATE is dropped" % label)
|
|
w.send(CTOS_CHAT, "hi".encode("utf-16-le") + b"\0\0")
|
|
pk = drain_all([h, g, w])
|
|
check(any(p == STOC_CHAT for p, _ in pk[w]), "%s: the observer's connection was kept" % label)
|
|
for payload, why in ((picking[:-1], "3 bytes"), (picking + b"\0", "5 bytes"),
|
|
(seat_state_bytes(STATE_PICKING, version=2), "version 2"), (seat_state_bytes(9), "state 9")):
|
|
g.send(CTOS_SEAT_STATE, payload)
|
|
pk = drain_all([h, g, w])
|
|
check(not any(seat_states(pk[c]) for c in (h, g, w)), "%s: a SEAT_STATE with %s is dropped (%s)" % (label, why, describe(pk[h])))
|
|
g.send(CTOS_CHAT, "hi".encode("utf-16-le") + b"\0\0")
|
|
pk = drain_all([h, g, w])
|
|
check(any(p == STOC_CHAT for p, _ in pk[g]), "%s: the guest's connection was kept" % label)
|
|
|
|
l = client("ss-late")
|
|
apps = [i for i, (p, d) in enumerate(l.log) if p == STOC_APPEARANCE and struct.unpack_from("<H", d, 0)[0] == 0]
|
|
sts = [i for i, (p, _) in enumerate(l.log) if p == STOC_SEAT_STATE]
|
|
check(seat_states(l.log) == [(0, picking)] and bool(apps) and bool(sts) and sts[0] == apps[0] + 1,
|
|
"%s: a late joiner gets one SEAT_STATE, stamped 0, right after seat 0's APPEARANCE (%s)" % (label, describe(l.log)))
|
|
drain_all([h, g, w])
|
|
|
|
h.send(CTOS_SEAT_STATE, none)
|
|
pk = drain_all([h, g, w, l])
|
|
check(all(seat_states(pk[c]) == [(0, none)] for c in (h, g, w, l)), "%s: none reaches everyone stamped 0" % label)
|
|
l2 = client("ss-late2")
|
|
check(not seat_states(l2.log), "%s: after none the snapshot carries no SEAT_STATE (%s)" % (label, describe(l2.log)))
|
|
drain_all([h, g, w, l])
|
|
|
|
h.send(CTOS_SEAT_STATE, picking)
|
|
drain_all(live())
|
|
h.send(CTOS_SEAT_SWAP, bytes([0, 1]))
|
|
pk = drain_all(live())
|
|
h.seat, g.seat = 1, 0
|
|
check(seat_states(pk[g]) == [(1, picking)], "%s: swap 0<->1: the state followed its owner, re-sent stamped 1 and nothing for seat 0 (%s)" % (label, describe(pk[g])))
|
|
ap = [i for i, (p, d) in enumerate(pk[g]) if p == STOC_APPEARANCE and struct.unpack_from("<H", d, 0)[0] == 1]
|
|
st = [i for i, (p, _) in enumerate(pk[g]) if p == STOC_SEAT_STATE]
|
|
check(bool(ap) and bool(st) and ap[0] < st[0], "%s: swap: APPEARANCE(1) comes before SEAT_STATE(1)" % label)
|
|
|
|
g.send(CTOS_SEAT_STATE, picking)
|
|
drain_all(live())
|
|
g.send(CTOS_LEAVE_GAME)
|
|
g.close()
|
|
g.closed = True
|
|
time.sleep(0.4)
|
|
drain_all(live())
|
|
l3 = client("ss-late3")
|
|
check(l3.seat == 0 and seat_states(l3.log) == [(1, picking)], "%s: the guest left: only the host's state (seat 1) is in the snapshot (seat %r, %s)" % (label, l3.seat, describe(l3.log)))
|
|
drain_all(live())
|
|
l3.send(CTOS_SEAT_STATE, picking)
|
|
drain_all(live())
|
|
l3.send(CTOS_SEAT_MOVE, bytes([0, WATCHERS]))
|
|
pk = drain_all(live())
|
|
l3.seat = OBSERVER
|
|
check(types(pk[l3]) == [OBSERVER], "%s: seat 0 moved to the watchers" % label)
|
|
l4 = client("ss-late4")
|
|
check(l4.seat == 0 and seat_states(l4.log) == [(1, picking)], "%s: after a move to the watchers that seat's state is gone (seat %r, %s)" % (label, l4.seat, describe(l4.log)))
|
|
drain_all(live())
|
|
|
|
seated = [c for c in live() if c.seat is not None and c.seat < seats]
|
|
check(len(seated) == seats, "%s: every seat is taken before the start (%s)" % (label, [(c.name, c.seat) for c in seated]))
|
|
hand = lambda c: 1 if c.seat == 0 else 2
|
|
for c in seated:
|
|
c.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pump(live(), lambda: False, limit=0.8, hand=hand)
|
|
h.send(CTOS_HS_START)
|
|
pump(live(), lambda: any(p == 0x15 for p, _ in h.log), limit=5, hand=hand)
|
|
check(any(p == 0x15 for p, _ in h.log), "%s: the duel started" % label)
|
|
l5 = client("ss-late5")
|
|
check(l5.seat == OBSERVER and not seat_states(l5.log), "%s: after START a late watcher's snapshot carries no SEAT_STATE (%s)" % (label, describe(l5.log[:10])))
|
|
h.send(CTOS_SEAT_STATE, picking)
|
|
pk = drain_all(live())
|
|
check(not any(seat_states(pk[c]) for c in live()), "%s: a SEAT_STATE during the duel is dropped" % label)
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, label)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def seat_state_suite(dll_path, port):
|
|
print()
|
|
print("hosting seat-state rooms from %s" % dll_path)
|
|
seat_state_room(dll_path, port, "single", 0)
|
|
seat_state_room(dll_path, port + 1, "tag", 2)
|
|
|
|
|
|
# --- patch 0014: lobby after match ------------------------------------------
|
|
STOC_MATCH_OVER, STOC_DUEL_END, STOC_DUEL_START = 0x5A, 0x16, 0x15
|
|
MSG_WIN = 5
|
|
NAMES.update({0x5A: "MATCH_OVER"})
|
|
|
|
|
|
def match_overs(pkts):
|
|
return [(struct.unpack_from("<H", d, 0)[0], d[2], d[3], tuple(d[4:8])) for p, d in pkts if p == STOC_MATCH_OVER and len(d) == 8]
|
|
|
|
|
|
def wins(pkts):
|
|
return [(d[1], d[2]) for p, d in pkts if p == 0x01 and len(d) == 3 and d[0] == MSG_WIN]
|
|
|
|
|
|
def ids_of(pkts):
|
|
return [p for p, _ in pkts]
|
|
|
|
|
|
def marks_of(clients):
|
|
return {c: len(c.log) for c in clients}
|
|
|
|
|
|
def since(c, marks):
|
|
return c.log[marks[c]:]
|
|
|
|
|
|
def alive(label, clients, what):
|
|
for c in clients:
|
|
c.send(CTOS_CHAT, "hi".encode("utf-16-le") + b"\0\0")
|
|
pk = drain_all(clients)
|
|
check(all(any(p == STOC_CHAT for p, _ in pk[c]) and not c.closed for c in clients), "%s: %s: every connection is still open (chat echoed)" % (label, what))
|
|
|
|
|
|
def start_duel_on(label, host, everyone, hand, what, tp=b"\x01", reporter=None):
|
|
# the duel exists only after the hand / turn-order prompts: special.lua's chat line says it does
|
|
reporter = reporter or host
|
|
before = len(probe_lines(reporter))
|
|
marks = marks_of(everyone)
|
|
host.send(CTOS_HS_START)
|
|
ok = pump(everyone, lambda: all(STOC_DUEL_START in ids_of(since(c, marks)) for c in everyone) and len(probe_lines(reporter)) > before, limit=15, hand=hand, tp=tp)
|
|
check(ok, "%s: %s: START played a duel on the same connections (DUEL_START to everyone: %s, special.lua ran: %s)" % (label, what, [(c.name, STOC_DUEL_START in ids_of(since(c, marks))) for c in everyone], len(probe_lines(reporter)) > before))
|
|
return marks
|
|
|
|
|
|
def ready_all(label, seated, everyone, hand):
|
|
for c in seated:
|
|
c.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pump(everyone, lambda: False, limit=0.8, hand=hand)
|
|
|
|
|
|
def expect_lobby_return(label, marks, everyone, duelists, what, seat_count, occupied, hand, leaver_seat=None, win_reason=None):
|
|
ok = pump(everyone, lambda: all(match_overs(since(c, marks)) for c in everyone), limit=10, hand=hand)
|
|
check(ok, "%s: %s: MATCH_OVER reached everyone (%s)" % (label, what, [(c.name, bool(match_overs(since(c, marks)))) for c in everyone]))
|
|
for c in everyone:
|
|
new = since(c, marks)
|
|
ids = ids_of(new)
|
|
if STOC_MATCH_OVER not in ids:
|
|
continue
|
|
i, j = ids.index(STOC_DUEL_END) if STOC_DUEL_END in ids else -1, ids.index(STOC_MATCH_OVER)
|
|
check(0 <= i < j, "%s: %s: %s got the stock DUEL_END before MATCH_OVER (%s)" % (label, what, c.name, describe(new[max(0, j - 6):j + 1])))
|
|
check(match_overs(new) == [(SERVER, 1, seat_count, occupied)],
|
|
"%s: %s: %s's MATCH_OVER is stamped 0xFF, version 1, %d seats, occupied %s (got %s)" % (label, what, c.name, seat_count, occupied, match_overs(new)))
|
|
check(not c.closed, "%s: %s: %s was not disconnected" % (label, what, c.name))
|
|
if leaver_seat is not None:
|
|
leaves = [k for k, p in enumerate(ids) if p == STOC_HS_PLAYER_CHANGE and new[k][1][0] == (leaver_seat << 4 | LEAVE)]
|
|
check(len(leaves) == 1 and i < leaves[0] < j, "%s: %s: %s saw PLAYER_CHANGE LEAVE for seat %d between DUEL_END and MATCH_OVER (%s)" % (label, what, c.name, leaver_seat, describe(new[i:j + 1])))
|
|
if win_reason is not None:
|
|
w = wins(new)
|
|
check(bool(w) and w[0][1] == win_reason and ids.index(0x01) < i, "%s: %s: %s got MSG_WIN reason %d before DUEL_END (%s)" % (label, what, c.name, win_reason, w))
|
|
for c in duelists:
|
|
check(any(p == STOC_REPLAY for p in ids_of(since(c, marks))), "%s: %s: %s got the replay" % (label, what, c.name))
|
|
|
|
|
|
def lobby_snapshot(label, port, name, what, enters_expected, clients, seat=OBSERVER):
|
|
l = Client("127.0.0.1", port, name)
|
|
l.log = list(l.join())
|
|
clients.append(l)
|
|
ready = [x for x in changes(l.log) if x & 0xF == READY]
|
|
check(l.seat == seat and enters(l.log) == enters_expected and not ready and STOC_DUEL_START not in ids_of(l.log),
|
|
"%s: %s: a joiner's snapshot is the lobby again: seat %r, enters %s, nobody READY, no DUEL_START (%s)" % (label, what, l.seat, enters(l.log), describe(l.log)))
|
|
return l
|
|
|
|
|
|
def lobby_single(dll_path, port, label):
|
|
print("== lobby after match, %s (2 seats: host, a claimed Cpu seat, a watcher)" % label)
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, 0)
|
|
clients = []
|
|
|
|
def client(name, claim=None):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join(claim=claim))
|
|
clients.append(c)
|
|
return c
|
|
|
|
def live():
|
|
return [c for c in clients if not c.closed]
|
|
|
|
tok = os.urandom(16)
|
|
h = client("lm-host")
|
|
h.send(CTOS_SEAT_PLAN, seat_plan_bytes(1, 2, [0, 1], [None, tok]))
|
|
drain_all([h])
|
|
c = client("lm-cpu", claim=(1, tok))
|
|
w = client("lm-watch")
|
|
check(h.seat == 0 and c.seat == 1 and w.seat == OBSERVER, "%s: host at 0, the CPU claimed seat 1, a watcher (%r %r %r)" % (label, h.seat, c.seat, w.seat))
|
|
for x in (h, w):
|
|
x.send(CTOS_CAPABILITY, capability_bytes(2, 0x1F))
|
|
h.send(CTOS_APPEARANCE, appearance_bytes(21))
|
|
drain_all([h, c, w])
|
|
hand = lambda x: 1 if x.seat == 0 else 2
|
|
|
|
ready_all(label, [h, c], [h, c, w], hand)
|
|
start_duel_on(label, h, [h, c, w], hand, "duel 1")
|
|
marks = marks_of([h, c, w])
|
|
h.send(CTOS_SURRENDER)
|
|
expect_lobby_return(label, marks, [h, c, w], [h, c], "surrender", 2, (1, 1, 0, 0), hand, win_reason=0)
|
|
alive(label, [h, c, w], "after the match")
|
|
l = lobby_snapshot(label, port, "lm-late", "after the match", [(0, "lm-host"), (1, "lm-cpu")], clients)
|
|
check(stamped(l.log, STOC_APPEARANCE, 0) == [appearance_bytes(21)] and plans(l.log) == [(SERVER, 1, 2, (0, 1, 0, 0))],
|
|
"%s: the snapshot still carries seat 0's APPEARANCE and the seat plan (kept across the match)" % label)
|
|
drain_all(live())
|
|
|
|
c.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pk = drain_all(live())
|
|
check(not changes(pk[h]) and not changes(pk[c]), "%s: the CPU's UpdateDeck loads WITHOUT readying it (held until the host's START) (%s)" % (label, describe(pk[h])))
|
|
c.send(CTOS_SEAT_RESUME, ZERO16 + bytes([1, 0]))
|
|
pk = drain_all(live())
|
|
check(resumes(pk[c]) == [(ZERO16, 1, 1, 0)] and not changes(pk[h]), "%s: the CPU completes its held seat with a zero restart id, READY still false (%s)" % (label, resumes(pk[c])))
|
|
c.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pk = drain_all(live())
|
|
check(changes(pk[h]) == [0x10 | READY], "%s: then the CPU's UpdateDeck readies seat 1 (0x19)" % label)
|
|
h.send(CTOS_SEAT_RESUME, ZERO16 + bytes([1, 0]))
|
|
pk = drain_all(live())
|
|
check(resumes(pk[h]) == [(ZERO16, 0, 0, 1)], "%s: a human is never held: its zero-id Complete is refused (reason 1)" % label)
|
|
h.send(CTOS_UPDATE_DECK, deck_bytes())
|
|
pk = drain_all(live())
|
|
check(changes(pk[c]) == [READY], "%s: the host's UpdateDeck readies seat 0 as usual (0x09)" % label)
|
|
|
|
l.send(CTOS_LEAVE_GAME)
|
|
l.close()
|
|
l.closed = True
|
|
time.sleep(0.4)
|
|
drain_all(live())
|
|
rid = os.urandom(16)
|
|
h.send(CTOS_RESTART_PREPARE, prepare_bytes(rid, 30000, 2, [os.urandom(16), os.urandom(16)], os.urandom(16)))
|
|
pk = drain_all(live())
|
|
check(restarting(pk[h]) and restarting(pk[h])[0][0] == PREPARE and restarting(pk[w]), "%s: EDIT is allowed again: Prepare after the match is accepted (phase 1 to everyone) (%s)" % (label, describe(pk[h])))
|
|
h.send(CTOS_RESTART_CONTROL, rid + bytes([ABORT]))
|
|
pk = drain_all(live())
|
|
check(restarting(pk[h]) and restarting(pk[h])[0][0] == ABORT, "%s: Abort unfreezes the room" % label)
|
|
|
|
start_duel_on(label, h, live(), hand, "duel 2")
|
|
marks = marks_of([h, w])
|
|
c.send(CTOS_LEAVE_GAME)
|
|
c.close()
|
|
c.closed = True
|
|
expect_lobby_return(label, marks, [h, w], [h], "the CPU left mid-duel", 2, (1, 0, 0, 0), hand, leaver_seat=1, win_reason=4)
|
|
alive(label, [h, w], "after the mid-duel leave")
|
|
lobby_snapshot(label, port, "lm-late2", "after the mid-duel leave", [(0, "lm-host")], clients)
|
|
drain_all(live())
|
|
c2 = client("lm-cpu2", claim=(1, tok))
|
|
check(c2.seat == 1, "%s: the leaver's Cpu seat is empty again: the token claims it (got %r)" % (label, c2.seat))
|
|
pk = drain_all(live())
|
|
check(enters(pk[h]) == [(1, "lm-cpu2")], "%s: the host saw the new claimant enter seat 1" % label)
|
|
for x in clients:
|
|
x.close()
|
|
stop_dll(dll, thread, label)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def lobby_match(dll_path, port, label):
|
|
print("== lobby after match, %s (Bo3: games 1-2 side, the decided match returns to the lobby)" % label)
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, 1)
|
|
clients = []
|
|
|
|
def client(name):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join())
|
|
clients.append(c)
|
|
return c
|
|
|
|
h = client("lm-mhost")
|
|
g = client("lm-mguest")
|
|
w = client("lm-mwatch")
|
|
check(h.seat == 0 and g.seat == 1 and w.seat == OBSERVER, "%s: host at 0, guest at 1, a watcher (%r %r %r)" % (label, h.seat, g.seat, w.seat))
|
|
drain_all([h, g, w])
|
|
hand = lambda x: 1 if x.seat == 0 else 2
|
|
everyone = [h, g, w]
|
|
|
|
ready_all(label, [h, g], everyone, hand)
|
|
start_duel_on(label, h, everyone, hand, "game 1")
|
|
ok = pump(everyone, lambda: len(probe_lines(h)) >= 1, limit=15, hand=hand)
|
|
check(ok and probe_lines(h)[0].endswith("count=0"), "%s: game 1 ran with duel_count=0 (%s)" % (label, probe_lines(h)))
|
|
marks = marks_of(everyone)
|
|
h.send(CTOS_SURRENDER)
|
|
# the loser picks the turn order of game 2 and goes SECOND, so the server swaps the seats for that game
|
|
ok = pump(everyone, lambda: len(probe_lines(h)) >= 2, limit=15, hand=hand, tp=b"\x00")
|
|
check(ok and probe_lines(h)[1].endswith("count=1"), "%s: game 2 followed through the siding path (duel_count=1)" % label)
|
|
for c in everyone:
|
|
new = since(c, marks)
|
|
check(STOC_MATCH_OVER not in ids_of(new) and STOC_DUEL_END not in ids_of(new), "%s: %s: game 1 ended with no DUEL_END and no MATCH_OVER (siding as before) (%s)" % (label, c.name, describe([x for x in new if x[0] != 0x01][:8])))
|
|
check(any(p == STOC_CHANGE_SIDE for p in ids_of(since(h, marks))), "%s: the host got CHANGE_SIDE after game 1" % label)
|
|
marks = marks_of(everyone)
|
|
h.send(CTOS_SURRENDER)
|
|
expect_lobby_return(label, marks, everyone, [h, g], "the decided match", 2, (1, 1, 0, 0), hand, win_reason=0)
|
|
check(len(replays(h)) == 2, "%s: two replays, one per game" % label)
|
|
check(ids_of(h.log).count(STOC_MATCH_OVER) == 1 and ids_of(h.log).count(STOC_DUEL_END) == 1, "%s: exactly one DUEL_END and one MATCH_OVER for the whole match" % label)
|
|
alive(label, everyone, "after the match")
|
|
l = lobby_snapshot(label, port, "lm-mlate", "after the match", [(0, "lm-mhost"), (1, "lm-mguest")], clients)
|
|
drain_all(everyone)
|
|
check(h.seat == 0 and g.seat == 1, "%s: the game-2 seat swap was undone: host 0, guest 1 in the lobby" % label)
|
|
|
|
marks = marks_of(everyone + [l])
|
|
ready_all(label, [h, g], everyone + [l], hand)
|
|
check(sorted(changes(since(w, marks))) == sorted([READY, 0x10 | READY]), "%s: both seats ready again from a plain UpdateDeck (%s)" % (label, describe(since(w, marks))))
|
|
start_duel_on(label, h, everyone + [l], hand, "match 2 game 1")
|
|
check(len(probe_lines(h)) >= 3 and probe_lines(h)[2].endswith("count=0"), "%s: the next match starts at duel_count=0 again (%s)" % (label, probe_lines(h)[2:]))
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, label)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def lobby_tag(dll_path, port, label):
|
|
print("== lobby after match, %s (4 seats + a watcher; the host leaves mid-duel)" % label)
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, 2)
|
|
clients = []
|
|
|
|
def client(name):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join())
|
|
clients.append(c)
|
|
return c
|
|
|
|
def live():
|
|
return [c for c in clients if not c.closed]
|
|
|
|
h, g1, g2, g3 = client("lm-thost"), client("lm-t1"), client("lm-t2"), client("lm-t3")
|
|
w = client("lm-twatch")
|
|
check([h.seat, g1.seat, g2.seat, g3.seat, w.seat] == [0, 1, 2, 3, OBSERVER], "%s: four seats and a watcher (%r)" % (label, [h.seat, g1.seat, g2.seat, g3.seat, w.seat]))
|
|
drain_all(live())
|
|
hand = lambda x: 1 if x.seat == 0 else 2
|
|
seated = [h, g1, g2, g3]
|
|
|
|
ready_all(label, seated, live(), hand)
|
|
start_duel_on(label, h, live(), hand, "duel 1")
|
|
marks = marks_of(live())
|
|
h.send(CTOS_SURRENDER)
|
|
g1.send(CTOS_SURRENDER) # a tag surrender needs both teammates
|
|
expect_lobby_return(label, marks, live(), seated, "surrender", 4, (1, 1, 1, 1), hand, win_reason=0)
|
|
alive(label, live(), "after the match")
|
|
lobby_snapshot(label, port, "lm-tlate", "after the match", [(0, "lm-thost"), (1, "lm-t1"), (2, "lm-t2"), (3, "lm-t3")], clients)
|
|
drain_all(live())
|
|
|
|
ready_all(label, seated, live(), hand)
|
|
start_duel_on(label, h, live(), hand, "duel 2")
|
|
others = [g1, g2, g3, w]
|
|
marks = marks_of(live())
|
|
h.send(CTOS_LEAVE_GAME)
|
|
h.close()
|
|
h.closed = True
|
|
expect_lobby_return(label, marks, others, [g1, g2, g3], "the host left mid-duel", 4, (0, 1, 1, 1), hand, leaver_seat=0)
|
|
# the server hands the room to the first seated human in its current (duel-order) list; the TYPE_CHANGE carries the lobby seat
|
|
handed = [(c, types(since(c, marks))) for c in (g1, g2, g3) if types(since(c, marks))]
|
|
check(len(handed) == 1 and handed[0][1] == [0x10 | handed[0][0].seat] and not types(since(w, marks)),
|
|
"%s: the room was handed to one seated human (TYPE_CHANGE 0x10|seat to it alone) once the lobby was back (%s)" % (label, [(c.name, t) for c, t in handed]))
|
|
new_host = handed[0][0] if handed else g1
|
|
alive(label, others, "after the host left")
|
|
l = lobby_snapshot(label, port, "lm-tnew", "after the host left", [(0, "lm-tnew"), (1, "lm-t1"), (2, "lm-t2"), (3, "lm-t3")], clients, seat=0)
|
|
drain_all(live())
|
|
ready_all(label, [l, g1, g2, g3], live(), hand)
|
|
drain_all(live())
|
|
start_duel_on(label, new_host, live(), hand, "the new host's duel 3")
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, label)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def lobby_suite(dll_path, port):
|
|
print()
|
|
print("hosting lobby-after-match rooms from %s" % dll_path)
|
|
lobby_single(dll_path, port, "single")
|
|
lobby_match(dll_path, port + 1, "match")
|
|
lobby_tag(dll_path, port + 2, "tag")
|
|
|
|
|
|
# --- patch 0017: coin toss ----------------------------------------------------
|
|
STOC_COIN_TOSS, STOC_TP_RESULT, STOC_HAND_RESULT = 0x5B, 0x06, 0x05
|
|
MSG_START = 4
|
|
FACE_HEADS, FACE_TAILS, FACE_NONE, CHOOSE_SECONDS = 0, 1, 0xFF, 10
|
|
NAMES.update({0x5B: "COIN_TOSS", 0x06: "TP_RESULT"})
|
|
|
|
|
|
def tosses(pkts):
|
|
return [tuple(d) for p, d in pkts if p == STOC_COIN_TOSS]
|
|
|
|
|
|
def starts(pkts):
|
|
return [d[1] for p, d in pkts if p == 0x01 and len(d) >= 2 and d[0] == MSG_START]
|
|
|
|
|
|
def check_toss(label, what, everyone, marks, chooser_seats, face_of, after_start):
|
|
first = tosses(since(everyone[0], marks))
|
|
if not check(len(first) == 1 and len(first[0]) == 4, "%s: %s: %s got exactly one 4-byte COIN_TOSS (%s)" % (label, what, everyone[0].name, describe([x for x in since(everyone[0], marks) if x[0] != 0x01][:10]))):
|
|
return None
|
|
version, chooser, face, seconds = first[0]
|
|
check(version == 1 and seconds == CHOOSE_SECONDS, "%s: %s: COIN_TOSS is version 1 with %d choose seconds (got %d / %d)" % (label, what, CHOOSE_SECONDS, version, seconds))
|
|
check(chooser in chooser_seats, "%s: %s: the chooser is one of %s (got %d)" % (label, what, chooser_seats, chooser))
|
|
check(face == face_of(chooser), "%s: %s: face %s matches chooser seat %d (got 0x%02x)" % (label, what, "0xFF none" if face_of(chooser) == FACE_NONE else "heads/tails", chooser, face))
|
|
for c in everyone:
|
|
new = since(c, marks)
|
|
idl = ids_of(new)
|
|
check(tosses(new) == [first[0]], "%s: %s: %s got the same COIN_TOSS, exactly once (%s)" % (label, what, c.name, tosses(new)))
|
|
check(STOC_SELECT_HAND not in idl and STOC_HAND_RESULT not in idl, "%s: %s: %s never saw SELECT_HAND or HAND_RESULT" % (label, what, c.name))
|
|
if STOC_COIN_TOSS not in idl:
|
|
continue
|
|
i = idl.index(STOC_COIN_TOSS)
|
|
if after_start:
|
|
check(STOC_DUEL_START in idl[:i], "%s: %s: %s got DUEL_START before the toss" % (label, what, c.name))
|
|
sel = [k for k, p in enumerate(idl) if p == STOC_SELECT_TP]
|
|
if c.seat == chooser:
|
|
check(len(sel) == 1 and sel[0] > i, "%s: %s: the chooser %s got SELECT_TP once, after the toss (%s)" % (label, what, c.name, describe(new[i:i + 3])))
|
|
else:
|
|
check(not sel, "%s: %s: %s (seat %r) got no SELECT_TP" % (label, what, c.name, c.seat))
|
|
return chooser
|
|
|
|
|
|
def check_first(label, what, everyone, marks, first_seats, swapped):
|
|
for c in everyone:
|
|
got = starts(since(c, marks))
|
|
if c.seat == OBSERVER:
|
|
want = [0x11 if swapped else 0x10]
|
|
else:
|
|
want = [0 if c.seat in first_seats else 1]
|
|
check(got == want, "%s: %s: %s's MSG_START player byte is %s (got %s)" % (label, what, c.name, want, got))
|
|
|
|
|
|
def coin_room(dll_path, port, label, mode):
|
|
seats = 4 if mode == 2 else 2
|
|
print("== coin toss, %s (%d seats + a watcher)" % (label, seats))
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, mode)
|
|
clients = []
|
|
|
|
def client(name):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join())
|
|
clients.append(c)
|
|
return c
|
|
|
|
seated = [client("ct-seat%d" % i) for i in range(seats)]
|
|
w = client("ct-watch")
|
|
everyone = seated + [w]
|
|
check([c.seat for c in everyone] == list(range(seats)) + [OBSERVER], "%s: %d seats and a watcher (%r)" % (label, seats, [c.seat for c in everyone]))
|
|
drain_all(everyone)
|
|
h = seated[0]
|
|
by_seat = {c.seat: c for c in seated}
|
|
chooser_seats = (0, 2) if mode == 2 else (0, 1)
|
|
face_of = (lambda s: s // 2) if mode == 2 else (lambda s: s)
|
|
team = (lambda s: (s, s + 1)) if mode == 2 else (lambda s: (s,))
|
|
|
|
ready_all(label, seated, everyone, None)
|
|
marks = marks_of(everyone)
|
|
t0 = time.time()
|
|
h.send(CTOS_HS_START)
|
|
pump(everyone, lambda: all(tosses(since(c, marks)) for c in everyone), limit=5, tp=None)
|
|
chooser = check_toss(label, "duel 1", everyone, marks, chooser_seats, face_of, after_start=True)
|
|
if chooser is None:
|
|
return
|
|
cc = by_seat[chooser]
|
|
others = [c for c in seated if c is not cc]
|
|
for c in seated:
|
|
c.send(CTOS_HAND_RESULT, bytes([1 + c.seat % 3]))
|
|
others[0].send(CTOS_TP_RESULT, b"\x00")
|
|
pk = drain_all(everyone, quiet=1.0)
|
|
check(not any(starts(pk[c]) or STOC_HAND_RESULT in ids_of(pk[c]) or c.closed for c in everyone),
|
|
"%s: duel 1: HAND_RESULT answers and the non-chooser's TP_RESULT change nothing (%s)" % (label, describe(pk[h])))
|
|
ok = pump(everyone, lambda: all(starts(since(c, marks)) for c in everyone), limit=16, tp=None)
|
|
elapsed = time.time() - t0
|
|
check(ok and 9.0 <= elapsed <= 14.0, "%s: duel 1: nobody answered: MSG_START reached everyone %.1f s after START (the %d s choose timer picked FIRST)" % (label, elapsed, CHOOSE_SECONDS))
|
|
check_first(label, "duel 1", everyone, marks, team(chooser), swapped=(chooser != 0))
|
|
cc.send(CTOS_TP_RESULT, b"\x00")
|
|
pk = drain_all(everyone, quiet=1.0)
|
|
check(not any(starts(pk[c]) or c.closed for c in everyone), "%s: duel 1: a TP_RESULT after the start changes nothing (no second MSG_START)" % label)
|
|
|
|
marks = marks_of(everyone)
|
|
for c in team(chooser):
|
|
by_seat[c].send(CTOS_SURRENDER)
|
|
ok = pump(everyone, lambda: all(match_overs(since(c, marks)) for c in everyone), limit=10, tp=None)
|
|
check(ok, "%s: the chooser's team surrendered: MATCH_OVER, the room is a lobby again" % label)
|
|
|
|
ready_all(label, seated, everyone, None)
|
|
marks = marks_of(everyone)
|
|
t0 = time.time()
|
|
h.send(CTOS_HS_START)
|
|
pump(everyone, lambda: all(tosses(since(c, marks)) for c in everyone), limit=5, tp=None)
|
|
chooser2 = check_toss(label, "duel 2", everyone, marks, chooser_seats, face_of, after_start=True)
|
|
if chooser2 is None:
|
|
return
|
|
cc2 = by_seat[chooser2]
|
|
cc2.send(CTOS_TP_RESULT, b"\x00")
|
|
ok = pump(everyone, lambda: all(starts(since(c, marks)) for c in everyone), limit=5, tp=None)
|
|
elapsed = time.time() - t0
|
|
check(ok and elapsed < 4.0, "%s: duel 2: the chooser answered SECOND: MSG_START at once (%.1f s)" % (label, elapsed))
|
|
other_team = tuple(s for s in range(seats) if s not in team(chooser2))
|
|
check_first(label, "duel 2", everyone, marks, other_team, swapped=(chooser2 == 0))
|
|
print(" waiting 11 s to prove the choose timer was cancelled")
|
|
time.sleep(11.0)
|
|
pk = drain_all(everyone, quiet=0.5)
|
|
check(all(len(starts(since(c, marks))) == 1 and not c.closed for c in everyone), "%s: duel 2: no second MSG_START 11 s later, nobody disconnected" % label)
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, label)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def coin_match(dll_path, port, label):
|
|
print("== coin toss, %s (Bo3: game 2 has no toss, the loser chooses on the same timer)" % label)
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, 1)
|
|
clients = []
|
|
|
|
def client(name):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join())
|
|
clients.append(c)
|
|
return c
|
|
|
|
h, g, w = client("ct-mhost"), client("ct-mguest"), client("ct-mwatch")
|
|
everyone = [h, g, w]
|
|
check([c.seat for c in everyone] == [0, 1, OBSERVER], "%s: host at 0, guest at 1, a watcher (%r)" % (label, [c.seat for c in everyone]))
|
|
drain_all(everyone)
|
|
by_seat = {0: h, 1: g}
|
|
|
|
ready_all(label, [h, g], everyone, None)
|
|
marks = marks_of(everyone)
|
|
h.send(CTOS_HS_START)
|
|
pump(everyone, lambda: all(tosses(since(c, marks)) for c in everyone), limit=5, tp=None)
|
|
chooser = check_toss(label, "game 1", everyone, marks, (0, 1), lambda s: s, after_start=True)
|
|
if chooser is None:
|
|
return
|
|
cc = by_seat[chooser]
|
|
cc.send(CTOS_TP_RESULT, b"\x01")
|
|
ok = pump(everyone, lambda: all(starts(since(c, marks)) for c in everyone), limit=5, tp=None)
|
|
check(ok, "%s: game 1: the chooser answered FIRST and the game started" % label)
|
|
check_first(label, "game 1", everyone, marks, (chooser,), swapped=(chooser != 0))
|
|
|
|
marks = marks_of(everyone)
|
|
t0 = time.time()
|
|
cc.send(CTOS_SURRENDER)
|
|
ok = pump(everyone, lambda: all(tosses(since(c, marks)) for c in everyone), limit=8, tp=None)
|
|
check(ok and STOC_CHANGE_SIDE in ids_of(since(h, marks)) and STOC_MATCH_OVER not in ids_of(since(h, marks)), "%s: game 1 lost by the chooser: siding, then a COIN_TOSS for game 2 (%s)" % (label, describe([x for x in since(h, marks) if x[0] != 0x01][:10])))
|
|
chooser2 = check_toss(label, "game 2", everyone, marks, (chooser,), lambda s: FACE_NONE, after_start=False)
|
|
if chooser2 is None:
|
|
return
|
|
ok = pump(everyone, lambda: all(starts(since(c, marks)) for c in everyone), limit=18, tp=None)
|
|
elapsed = time.time() - t0
|
|
check(ok and 9.0 <= elapsed <= 15.0, "%s: game 2: nobody answered: MSG_START %.1f s after the surrender (the choose timer picked FIRST for the loser)" % (label, elapsed))
|
|
check_first(label, "game 2", everyone, marks, (chooser,), swapped=(chooser != 0))
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, label)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def coin_toss_suite(dll_path, port):
|
|
print()
|
|
print("hosting coin-toss rooms from %s" % dll_path)
|
|
coin_room(dll_path, port, "single", 0)
|
|
coin_match(dll_path, port + 1, "match")
|
|
coin_room(dll_path, port + 2, "tag", 2)
|
|
|
|
|
|
# --- patch 0018: spectators see all -------------------------------------------
|
|
MSG_DRAW, MSG_UPDATE_DATA, LOCATION_HAND = 90, 6, 0x02
|
|
SPECTATOR_HIDDEN = "ygol.room.spectatorview=hidden"
|
|
|
|
|
|
def game_msgs(pkts, kind):
|
|
return [d for p, d in pkts if p == 0x01 and len(d) > 0 and d[0] == kind]
|
|
|
|
|
|
def draws(pkts, player=None):
|
|
return [d for d in game_msgs(pkts, MSG_DRAW) if len(d) >= 3 and (player is None or d[1] == player)]
|
|
|
|
|
|
def draw_codes(d):
|
|
return list(struct.unpack_from("<%di" % d[2], d, 3))
|
|
|
|
|
|
def hand_updates(pkts, player=None):
|
|
return [d for d in game_msgs(pkts, MSG_UPDATE_DATA) if len(d) >= 3 and d[2] == LOCATION_HAND and (player is None or d[1] == player)]
|
|
|
|
|
|
def card_codes(update):
|
|
# per card: int32 len (self-inclusive), uint32 flags, int32 code, int32 position info; a masked card is all zeros after its len
|
|
out, off = [], 3
|
|
while off + 4 <= len(update):
|
|
(clen,) = struct.unpack_from("<i", update, off)
|
|
if clen < 4:
|
|
break
|
|
out.append(struct.unpack_from("<i", update, off + 8)[0] if clen >= 12 else 0)
|
|
off += clen
|
|
return out
|
|
|
|
|
|
def spectator_room(dll_path, port, label, mode, hidden):
|
|
seats = 4 if mode == 2 else 2
|
|
what = "hidden" if hidden else "see all"
|
|
tag = "%s, %s" % (label, what)
|
|
print("== spectators, %s (%d seats + a watcher, then a late watcher)" % (tag, seats))
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, mode, SPECTATOR_HIDDEN if hidden else "")
|
|
clients = []
|
|
|
|
def client(name):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join())
|
|
clients.append(c)
|
|
return c
|
|
|
|
seated = [client("sp-seat%d" % i) for i in range(seats)]
|
|
w = client("sp-watch")
|
|
everyone = seated + [w]
|
|
check([c.seat for c in everyone] == list(range(seats)) + [OBSERVER], "%s: %d seats and a watcher (%r)" % (tag, seats, [c.seat for c in everyone]))
|
|
drain_all(everyone)
|
|
ready_all(tag, seated, everyone, None)
|
|
marks = start_duel_on(label, seated[0], everyone, None, what)
|
|
ok = pump(everyone, lambda: all(len(draws(since(c, marks))) >= 2 for c in everyone), limit=10)
|
|
check(ok, "%s: the opening draws reached every seat and the watcher (%s)" % (tag, [(c.name, len(draws(since(c, marks)))) for c in everyone]))
|
|
by_player = {}
|
|
for c in seated:
|
|
s = starts(since(c, marks))
|
|
by_player.setdefault(s[0] if len(s) == 1 else -1, []).append(c)
|
|
if not check(sorted(by_player) == [0, 1] and all(len(v) == seats // 2 for v in by_player.values()),
|
|
"%s: every seat got one MSG_START naming its side (%s)" % (tag, {k: [c.name for c in v] for k, v in by_player.items()})):
|
|
return
|
|
check(starts(since(w, marks)) in ([0x10], [0x11]), "%s: the watcher's MSG_START byte is 0x10 / 0x11 (%s)" % (tag, starts(since(w, marks))))
|
|
for p in (0, 1):
|
|
owner, other = by_player[p][0], by_player[1 - p][0]
|
|
wd, od, xd = draws(since(w, marks), p), draws(since(owner, marks), p), draws(since(other, marks), p)
|
|
check(len(wd) >= 1 and len(wd) == len(od) == len(xd), "%s: side %d drew; the watcher got every MSG_DRAW the seats got (%d / %d / %d)" % (tag, p, len(wd), len(od), len(xd)))
|
|
for k in range(min(len(wd), len(od), len(xd))):
|
|
check(all(c == PROBE_CARD for c in draw_codes(od[k])), "%s: side %d's own DRAW %d carries its codes" % (tag, p, k))
|
|
check(all(c == 0 for c in draw_codes(xd[k])), "%s: side %d's DRAW %d reaches the other side with codes zeroed" % (tag, p, k))
|
|
if hidden:
|
|
check(wd[k] == xd[k], "%s: the watcher's DRAW %d of side %d is the other side's masked copy, byte for byte" % (tag, k, p))
|
|
else:
|
|
check(wd[k] == od[k], "%s: the watcher's DRAW %d of side %d is the owner's full copy, byte for byte" % (tag, k, p))
|
|
wh, oh, xh = hand_updates(since(w, marks), p), hand_updates(since(owner, marks), p), hand_updates(since(other, marks), p)
|
|
check(len(wh) >= 1 and len(wh) == len(oh) == len(xh), "%s: side %d's hand refreshes reached the watcher as often as the seats (%d / %d / %d)" % (tag, p, len(wh), len(oh), len(xh)))
|
|
for k in range(min(len(wh), len(oh), len(xh))):
|
|
check(any(c == PROBE_CARD for c in card_codes(oh[k])), "%s: side %d's own hand refresh %d carries its codes" % (tag, p, k))
|
|
check(all(c == 0 for c in card_codes(xh[k])), "%s: side %d's hand refresh %d reaches the other side zeroed" % (tag, p, k))
|
|
if hidden:
|
|
check(wh[k] == xh[k], "%s: the watcher's hand refresh %d of side %d is the other side's masked copy, byte for byte" % (tag, k, p))
|
|
else:
|
|
check(wh[k] == oh[k], "%s: the watcher's hand refresh %d of side %d is the owner's full copy, byte for byte" % (tag, k, p))
|
|
|
|
l = client("sp-late")
|
|
l.log += l.drain(quiet=0.6)
|
|
check(l.seat == OBSERVER and STOC_DUEL_START in ids_of(l.log), "%s: a mid-duel joiner is an observer and got DUEL_START" % tag)
|
|
snap = hand_updates(l.log)
|
|
check(sorted(d[1] for d in snap) == [0, 1], "%s: the late watcher's snapshot refreshed both hands (%s)" % (tag, [d[1] for d in snap]))
|
|
for d in snap:
|
|
codes = card_codes(d)
|
|
check(len(codes) >= 5, "%s: the snapshot hand of side %d has its cards (%d)" % (tag, d[1], len(codes)))
|
|
if hidden:
|
|
check(all(c == 0 for c in codes), "%s: the late watcher's hand of side %d is zeroed (%s)" % (tag, d[1], codes))
|
|
else:
|
|
check(codes and all(c == PROBE_CARD for c in codes), "%s: the late watcher's hand of side %d carries every code (%s)" % (tag, d[1], codes))
|
|
|
|
marks = marks_of(everyone + [l])
|
|
for c in by_player[0]:
|
|
c.send(CTOS_SURRENDER)
|
|
ok = pump(everyone + [l], lambda: all(match_overs(since(c, marks)) for c in everyone + [l]), limit=10)
|
|
check(ok, "%s: side 0 surrendered: MATCH_OVER reached everyone, the late watcher included" % tag)
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, tag)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def spectator_suite(dll_path, port):
|
|
print()
|
|
print("hosting spectator rooms from %s" % dll_path)
|
|
spectator_room(dll_path, port, "single", 0, hidden=False)
|
|
spectator_room(dll_path, port + 1, "single", 0, hidden=True)
|
|
spectator_room(dll_path, port + 2, "tag", 2, hidden=False)
|
|
spectator_room(dll_path, port + 3, "tag", 2, hidden=True)
|
|
|
|
|
|
# --- patch 0019: deck lists -----------------------------------------------------
|
|
STOC_DECK_LIST, CTOS_RESPONSE, CTOS_TIME_CONFIRM, MSG_SELECT_IDLECMD, MSG_SELECT_CHAIN, MSG_TAG_SWAP = 0x5C, 0x01, 0x15, 11, 16, 161
|
|
NAMES.update({0x5C: "DECK_LIST"})
|
|
# four decks of 40 distinct codes, one per lobby seat (make_workspace puts them in the cdb)
|
|
DECK_LIST_CODES = [[PROBE_CARD + 1 + seat * 40 + i for i in range(40)] for seat in range(4)]
|
|
|
|
|
|
def deck_lists(pkts, side=None, kind=None):
|
|
out = []
|
|
for p, d in pkts:
|
|
if p != STOC_DECK_LIST or len(d) < 5:
|
|
continue
|
|
version, s, k, count = struct.unpack_from("<BBBH", d, 0)
|
|
codes = list(struct.unpack_from("<%dI" % count, d, 5)) if len(d) == 5 + 4 * count else None
|
|
if version == 1 and (side is None or s == side) and (kind is None or k == kind):
|
|
out.append((s, k, codes))
|
|
return out
|
|
|
|
|
|
def latest_codes(pkts, side, kind):
|
|
lists = deck_lists(pkts, side, kind)
|
|
return lists[-1][2] if lists else None
|
|
|
|
|
|
def deck_list_room(dll_path, port, label, mode, hidden):
|
|
seats = 4 if mode == 2 else 2
|
|
what = "hidden" if hidden else "see all"
|
|
tag = "%s, %s" % (label, what)
|
|
print("== deck lists, %s (%d seats + a watcher, two turn passes, then a late watcher)" % (tag, seats))
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, mode, SPECTATOR_HIDDEN if hidden else "")
|
|
clients = []
|
|
|
|
def client(name):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join())
|
|
clients.append(c)
|
|
return c
|
|
|
|
seated = [client("dl-seat%d" % i) for i in range(seats)]
|
|
w = client("dl-watch")
|
|
everyone = seated + [w]
|
|
check([c.seat for c in everyone] == list(range(seats)) + [OBSERVER], "%s: %d seats and a watcher (%r)" % (tag, seats, [c.seat for c in everyone]))
|
|
drain_all(everyone)
|
|
for c in seated:
|
|
c.send(CTOS_UPDATE_DECK, deck_bytes(DECK_LIST_CODES[c.seat]))
|
|
pump(everyone, lambda: False, limit=0.8)
|
|
marks = start_duel_on(label, seated[0], everyone, None, what)
|
|
ok = pump(everyone, lambda: all(len(draws(since(c, marks))) >= 2 for c in everyone) and any(game_msgs(since(c, marks), MSG_SELECT_IDLECMD) for c in seated), limit=10)
|
|
check(ok, "%s: the opening draws and the first idle prompt reached the seats" % tag)
|
|
side_of = {}
|
|
for c in seated:
|
|
s = starts(since(c, marks))
|
|
side_of[c] = s[0] if len(s) == 1 else -1
|
|
by_side = {p: [c for c in seated if side_of[c] == p] for p in (0, 1)}
|
|
if not check(all(len(by_side[p]) == seats // 2 for p in (0, 1)), "%s: every seat got one MSG_START naming its side (%s)" % (tag, {k: [c.name for c in v] for k, v in by_side.items()})):
|
|
return
|
|
first_seat = {p: min(c.seat for c in by_side[p]) for p in (0, 1)}
|
|
partner_seat = {p: max(c.seat for c in by_side[p]) for p in (0, 1)}
|
|
|
|
def drawn(c, p, since_marks):
|
|
return [x for d in draws(since(c, since_marks), p) for x in draw_codes(d)]
|
|
|
|
def check_owner_lists(p, since_marks, expect_remaining, stage):
|
|
for c in by_side[p]:
|
|
mine = deck_lists(since(c, since_marks), p, 0)
|
|
check(mine and all(x[2] is not None for x in mine), "%s: %s: seat %d got kind-0 DECK_LIST(s) for its side %d (%d)" % (tag, stage, c.seat, p, len(mine)))
|
|
check(not deck_lists(since(c, since_marks), 1 - p) and not deck_lists(since(c, since_marks), p, 1) and not deck_lists(since(c, since_marks), p, 2),
|
|
"%s: %s: seat %d got no list for the other side and never kinds 1 / 2" % (tag, stage, c.seat))
|
|
codes = latest_codes(since(c, since_marks), p, 0)
|
|
if codes is None:
|
|
continue
|
|
check(codes == sorted(codes), "%s: %s: seat %d's kind-0 list is sorted" % (tag, stage, c.seat))
|
|
check(codes == expect_remaining, "%s: %s: seat %d's kind-0 list is the submitted deck minus the drawn cards (%d cards; expected %d)" % (tag, stage, c.seat, len(codes), len(expect_remaining)))
|
|
|
|
def check_watcher_lists(p, since_marks, expect_remaining, expect_submitted, stage, full_again=True):
|
|
lists = deck_lists(since(w, since_marks), p)
|
|
if hidden:
|
|
check(not lists, "%s: %s: the hidden watcher got no DECK_LIST for side %d (%d)" % (tag, stage, p, len(lists)))
|
|
return
|
|
order = latest_codes(since(w, since_marks), p, 1)
|
|
full = latest_codes(since(w, since_marks), p, 2)
|
|
check(order is not None and not deck_lists(since(w, since_marks), p, 0), "%s: %s: the watcher got kind 1 for side %d and never kind 0" % (tag, stage, p))
|
|
if full_again:
|
|
check(full is not None, "%s: %s: the watcher got kind 2 for side %d" % (tag, stage, p))
|
|
else:
|
|
check(full is None, "%s: %s: the unchanged submitted deck of side %d was not sent again" % (tag, stage, p))
|
|
if order is not None:
|
|
check(sorted(order) == expect_remaining, "%s: %s: the watcher's kind-1 list of side %d holds the remaining cards (%d)" % (tag, stage, p, len(order)))
|
|
check(order != sorted(order), "%s: %s: the watcher's kind-1 list of side %d is an order, not the sorted list" % (tag, stage, p))
|
|
if full is not None:
|
|
check(full == expect_submitted, "%s: %s: the watcher's kind-2 list of side %d is the submitted Main Deck in the zone, sorted (%d)" % (tag, stage, p, len(full)))
|
|
return order
|
|
|
|
tops = {}
|
|
for p in (0, 1):
|
|
owner = by_side[p][0]
|
|
remaining = sorted(set(DECK_LIST_CODES[first_seat[p]]) - set(drawn(owner, p, marks)))
|
|
check(len(remaining) in (35, 34), "%s: side %d drew its opening hand (%d left)" % (tag, p, len(remaining)))
|
|
check_owner_lists(p, marks, remaining, "opening")
|
|
tops[p] = check_watcher_lists(p, marks, remaining, sorted(DECK_LIST_CODES[first_seat[p]]), "opening")
|
|
|
|
def end_turn(stage):
|
|
holders = [c for c in seated if game_msgs(since(c, end_turn.marks), MSG_SELECT_IDLECMD)]
|
|
check(len(holders) == 1, "%s: %s: exactly one seat holds the idle prompt (%s)" % (tag, stage, [c.name for c in holders]))
|
|
if not holders:
|
|
return None
|
|
before = marks_of(everyone)
|
|
holders[0].send(CTOS_TIME_CONFIRM) # the timed server holds the seat at CTOS_TIME_CONFIRM until the clock is acknowledged
|
|
holders[0].send(CTOS_RESPONSE, struct.pack("<i", 7)) # idle command 7: to the End Phase
|
|
ok = pump(everyone, lambda: any(draws(since(c, before)) for c in seated) and any(game_msgs(since(c, before), MSG_SELECT_IDLECMD) for c in seated), limit=10, chain=True)
|
|
check(ok, "%s: %s: the turn passed and the next seat drew" % (tag, stage))
|
|
end_turn.marks = before
|
|
return before
|
|
end_turn.marks = marks
|
|
|
|
# turn 1 -> 2: the other side draws its top card
|
|
before = end_turn("pass 1")
|
|
if before:
|
|
q = [p for p in (0, 1) if any(draws(since(c, before), p) for c in seated)]
|
|
check(len(q) == 1, "%s: pass 1: one side drew (%s)" % (tag, q))
|
|
if q:
|
|
q = q[0]
|
|
owner = by_side[q][0]
|
|
card = drawn(owner, q, before)
|
|
check(len(card) == 1, "%s: pass 1: side %d drew one card" % (tag, q))
|
|
if not hidden and tops.get(q) and card:
|
|
check(tops[q][0] == card[0], "%s: pass 1: the drawn card is the first code of the watcher's kind-1 list (top first)" % tag)
|
|
remaining = sorted(set(DECK_LIST_CODES[first_seat[q]]) - set(drawn(owner, q, marks)))
|
|
check_owner_lists(q, before, remaining, "pass 1")
|
|
check_watcher_lists(q, before, remaining, sorted(DECK_LIST_CODES[first_seat[q]]), "pass 1", full_again=False)
|
|
check(not deck_lists(since(w, before), 1 - q) or hidden, "%s: pass 1: the untouched side %d sent the watcher no new list" % (tag, 1 - q))
|
|
for c in by_side[1 - q]:
|
|
check(not deck_lists(since(c, before)), "%s: pass 1: seat %d (the other side) got no list" % (tag, c.seat))
|
|
|
|
# turn 2 -> 3: in Tag the first team swaps to its partner's deck
|
|
before = end_turn("pass 2")
|
|
if before and mode == 2:
|
|
swaps = [d[1] for d in game_msgs(since(w, before), MSG_TAG_SWAP) if len(d) > 1]
|
|
check(swaps == [0], "%s: pass 2: the watcher saw one MSG_TAG_SWAP for side 0 (%s)" % (tag, swaps))
|
|
if not hidden:
|
|
full = latest_codes(since(w, before), 0, 2)
|
|
check(full == sorted(DECK_LIST_CODES[partner_seat[0]]), "%s: pass 2: the watcher's kind-2 list of side 0 is now the PARTNER's submitted deck" % tag)
|
|
order = latest_codes(since(w, before), 0, 1)
|
|
mine = latest_codes(since(by_side[0][0], before), 0, 0)
|
|
check(order is not None and mine is not None and sorted(order) == mine, "%s: pass 2: the watcher's kind-1 list of side 0 holds the same cards as the owners' kind-0 list" % tag)
|
|
for c in by_side[0]:
|
|
codes = latest_codes(since(c, before), 0, 0)
|
|
check(codes is not None and set(codes) <= set(DECK_LIST_CODES[partner_seat[0]]), "%s: pass 2: seat %d's kind-0 list is from the partner's deck" % (tag, c.seat))
|
|
if hidden:
|
|
check(not deck_lists(since(w, before)), "%s: pass 2: the hidden watcher still got no DECK_LIST" % tag)
|
|
|
|
l = client("dl-late")
|
|
l.log += l.drain(quiet=0.6)
|
|
check(l.seat == OBSERVER and STOC_DUEL_START in ids_of(l.log), "%s: a mid-duel joiner is an observer and got DUEL_START" % tag)
|
|
snap = deck_lists(l.log)
|
|
if hidden:
|
|
check(not snap, "%s: the late hidden watcher's snapshot has no DECK_LIST (%d)" % (tag, len(snap)))
|
|
else:
|
|
check(sorted((s, k) for s, k, _ in snap) == [(0, 1), (0, 2), (1, 1), (1, 2)], "%s: the late watcher's snapshot has kinds 1 and 2 for both sides, once each (%s)" % (tag, sorted((s, k) for s, k, _ in snap)))
|
|
for p in (0, 1):
|
|
order = latest_codes(l.log, p, 1)
|
|
mine = latest_codes(by_side[p][0].log[marks[by_side[p][0]]:], p, 0)
|
|
check(order is not None and mine is not None and sorted(order) == mine, "%s: the late watcher's kind-1 list of side %d holds the owners' current cards" % (tag, p))
|
|
check(latest_codes(l.log, p, 2) == latest_codes(w.log[marks[w]:], p, 2), "%s: the late watcher's kind-2 list of side %d matches the first watcher's" % (tag, p))
|
|
|
|
marks2 = marks_of(everyone + [l])
|
|
for c in by_side[0]:
|
|
c.send(CTOS_SURRENDER)
|
|
ok = pump(everyone + [l], lambda: all(match_overs(since(c, marks2)) for c in everyone + [l]), limit=10)
|
|
check(ok, "%s: side 0 surrendered: MATCH_OVER reached everyone, the late watcher included" % tag)
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, tag)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def deck_list_suite(dll_path, port):
|
|
print()
|
|
print("hosting deck list rooms from %s" % dll_path)
|
|
deck_list_room(dll_path, port, "single", 0, hidden=False)
|
|
deck_list_room(dll_path, port + 1, "single", 0, hidden=True)
|
|
deck_list_room(dll_path, port + 2, "tag", 2, hidden=False)
|
|
deck_list_room(dll_path, port + 3, "tag", 2, hidden=True)
|
|
|
|
|
|
# --- patch 0020: profile --------------------------------------------------------
|
|
CTOS_PROFILE = STOC_PROFILE = 0x5D
|
|
NAMES.update({0x5D: "PROFILE"})
|
|
|
|
|
|
def profile_bytes(avatar, frame="", version=1):
|
|
return struct.pack("<BB", version, 0) + utf16(avatar, 32) + utf16(frame, 16)
|
|
|
|
|
|
def profiles(pkts):
|
|
return [(struct.unpack_from("<H", d, 0)[0], d[2:]) for p, d in pkts if p == STOC_PROFILE and len(d) == 100]
|
|
|
|
|
|
def profile_room(dll_path, port, label, mode):
|
|
seats = 4 if mode == 2 else 2
|
|
cpu_seat = seats - 1
|
|
print("== profile, %s (%d seats, seat %d a claimed Cpu seat)" % (label, seats, cpu_seat))
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, mode)
|
|
clients = []
|
|
|
|
def client(name, claim=None):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join(claim=claim))
|
|
clients.append(c)
|
|
return c
|
|
|
|
def live():
|
|
return [c for c in clients if not c.closed]
|
|
|
|
tok = os.urandom(16)
|
|
h = client("pf-host")
|
|
h.send(CTOS_SEAT_PLAN, seat_plan_bytes(1, seats, [0] * cpu_seat + [1], [None] * cpu_seat + [tok]))
|
|
drain_all([h])
|
|
humans = [h] + [client("pf-guest%d" % i) for i in range(1, cpu_seat)]
|
|
b = client("pf-cpu", claim=(cpu_seat, tok))
|
|
w = client("pf-watch")
|
|
check([c.seat for c in humans] == list(range(cpu_seat)) and b.seat == cpu_seat and w.seat == OBSERVER,
|
|
"%s: humans at 0..%d, the CPU claimed seat %d, a watcher (%r %r %r)" % (label, cpu_seat - 1, cpu_seat, [c.seat for c in humans], b.seat, w.seat))
|
|
h.send(CTOS_APPEARANCE, appearance_bytes(31))
|
|
drain_all(live())
|
|
|
|
atem, mai = profile_bytes("atem", "gold"), profile_bytes("mai-ori")
|
|
h.send(CTOS_PROFILE, atem)
|
|
pk = drain_all(live())
|
|
check(len(atem) == 98 and all(profiles(pk[c]) == [(0, atem)] for c in live()),
|
|
"%s: the host's 98-byte PROFILE reaches everyone stamped 0, byte-identical (%s)" % (label, describe(pk[w])))
|
|
b.send(CTOS_PROFILE, mai)
|
|
pk = drain_all(live())
|
|
check(not any(profiles(pk[c]) for c in live()), "%s: a CPU seat's PROFILE is dropped" % label)
|
|
w.send(CTOS_PROFILE, mai)
|
|
pk = drain_all(live())
|
|
check(not any(profiles(pk[c]) for c in live()), "%s: an observer's PROFILE is dropped" % label)
|
|
w.send(CTOS_CHAT, "hi".encode("utf-16-le") + b"\0\0")
|
|
pk = drain_all(live())
|
|
check(any(p == STOC_CHAT for p, _ in pk[w]), "%s: the observer's connection was kept" % label)
|
|
for payload, why in ((mai[:-1], "97 bytes"), (mai + b"\0", "99 bytes"), (profile_bytes("mai-ori", version=2), "version 2")):
|
|
h.send(CTOS_PROFILE, payload)
|
|
pk = drain_all(live())
|
|
check(not any(profiles(pk[c]) for c in live()), "%s: a PROFILE with %s is dropped (%s)" % (label, why, describe(pk[w])))
|
|
h.send(CTOS_CHAT, "hi".encode("utf-16-le") + b"\0\0")
|
|
pk = drain_all(live())
|
|
check(any(p == STOC_CHAT for p, _ in pk[h]), "%s: the host's connection was kept" % label)
|
|
|
|
l = client("pf-late")
|
|
apps = [i for i, (p, d) in enumerate(l.log) if p == STOC_APPEARANCE and struct.unpack_from("<H", d, 0)[0] == 0]
|
|
pfs = [i for i, (p, _) in enumerate(l.log) if p == STOC_PROFILE]
|
|
check(profiles(l.log) == [(0, atem)] and bool(apps) and bool(pfs) and pfs[0] > apps[0],
|
|
"%s: a late joiner gets one PROFILE, stamped 0, after seat 0's APPEARANCE, none for the CPU (%s)" % (label, describe(l.log)))
|
|
drain_all(live())
|
|
|
|
h.send(CTOS_PROFILE, mai)
|
|
drain_all(live())
|
|
l2 = client("pf-late2")
|
|
check(profiles(l2.log) == [(0, mai)], "%s: a newer PROFILE replaces the stored one (%s)" % (label, describe(l2.log)))
|
|
drain_all(live())
|
|
if len(humans) > 1:
|
|
humans[1].send(CTOS_PROFILE, atem)
|
|
drain_all(live())
|
|
|
|
h.send(CTOS_SEAT_SWAP, bytes([0, 1]))
|
|
pk = drain_all(live())
|
|
moved = humans[1] if len(humans) > 1 else b
|
|
h.seat, moved.seat = 1, 0
|
|
expect = sorted([(1, mai)] + ([(0, atem)] if moved is not b else []))
|
|
check(sorted(profiles(pk[w])) == expect, "%s: swap 0<->1: each profile followed its owner, re-sent stamped with the new seat (%s)" % (label, profiles(pk[w])))
|
|
l3 = client("pf-late3")
|
|
check(sorted(profiles(l3.log)) == expect, "%s: after the swap the snapshot carries the profiles at their new seats (%s)" % (label, describe(l3.log)))
|
|
drain_all(live())
|
|
|
|
seated = [c for c in live() if c.seat is not None and c.seat < seats]
|
|
hand = lambda x: 1 if x.seat == 0 else 2
|
|
ready_all(label, seated, live(), hand)
|
|
start_duel_on(label, h, live(), hand, "duel 1")
|
|
marks = marks_of(live())
|
|
for c in seated:
|
|
if c.seat in (0, 1) and c is not b:
|
|
c.send(CTOS_SURRENDER)
|
|
expect_lobby_return(label, marks, live(), seated, "surrender", seats, tuple([1] * seats + [0] * (4 - seats)), hand, win_reason=0)
|
|
l4 = client("pf-late4")
|
|
check(sorted(profiles(l4.log)) == expect, "%s: the profiles survive the lobby reset (%s)" % (label, profiles(l4.log)))
|
|
drain_all(live())
|
|
|
|
h.send(CTOS_SEAT_MOVE, bytes([1, WATCHERS]))
|
|
drain_all(live())
|
|
h.seat = OBSERVER
|
|
l5 = client("pf-late5")
|
|
check(l5.seat == 1 and (1, mai) not in profiles(l5.log), "%s: a seat moved to the watchers loses its profile; a newcomer takes it clean (seat %r, %s)" % (label, l5.seat, profiles(l5.log)))
|
|
drain_all(live())
|
|
l5.send(CTOS_PROFILE, atem)
|
|
pk = drain_all(live())
|
|
check(profiles(pk[w]) == [(1, atem)], "%s: the newcomer at seat 1 sends its own (%s)" % (label, profiles(pk[w])))
|
|
l5.send(CTOS_LEAVE_GAME)
|
|
l5.close()
|
|
l5.closed = True
|
|
time.sleep(0.4)
|
|
drain_all(live())
|
|
l6 = client("pf-late6")
|
|
check(not [x for x in profiles(l6.log) if x[0] == 1], "%s: a seat that leaves loses its profile (%s)" % (label, profiles(l6.log)))
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, label)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def profile_suite(dll_path, port):
|
|
print()
|
|
print("hosting profile rooms from %s" % dll_path)
|
|
profile_room(dll_path, port, "single", 0)
|
|
profile_room(dll_path, port + 1, "tag", 2)
|
|
|
|
|
|
# --- patch 0023: attack preview --------------------------------------------------
|
|
CTOS_ATTACK_PREVIEW = STOC_ATTACK_PREVIEW = 0x5E
|
|
NAMES.update({0x5E: "ATTACK_PREVIEW"})
|
|
MSG_SELECT_BATTLECMD, MSG_SELECT_PLACE, MZONE, DIRECT = 10, 18, 0x04, 0xFF
|
|
PREVIEW_ANSWER = 24
|
|
|
|
|
|
def preview_ask(pairs, version=1, count=None):
|
|
body = b"".join(struct.pack("<4B", *pr) for pr in pairs)
|
|
return struct.pack("<BB", version, len(pairs) if count is None else count) + body
|
|
|
|
|
|
def previews(pkts):
|
|
out = []
|
|
for p, d in pkts:
|
|
if p != STOC_ATTACK_PREVIEW or len(d) < 2:
|
|
continue
|
|
n = d[1]
|
|
pairs = [(tuple(d[2 + i * 28:6 + i * 28]), bytes(d[6 + i * 28:30 + i * 28])) for i in range(n)]
|
|
out.append((d[0], n, pairs, len(d)))
|
|
return out
|
|
|
|
|
|
def preview_answer(flags, attacker=0, target=0, damage0=0, damage1=0):
|
|
return struct.pack("<BBHiiiii", 1, flags, 0, attacker, target, damage0, damage1, 0)
|
|
|
|
|
|
def attack_preview_room(dll_path, port, label, mode):
|
|
seats = 4 if mode == 2 else 2
|
|
print("== attack preview, %s (%d seats + a watcher: a summon each, then the second seat's Battle Phase)" % (label, seats))
|
|
root = make_workspace()
|
|
here = os.getcwd()
|
|
os.chdir(root)
|
|
try:
|
|
write_special(root, [])
|
|
dll, thread = host_dll(dll_path, port, mode)
|
|
clients = []
|
|
|
|
def client(name):
|
|
c = Client("127.0.0.1", port, name)
|
|
c.log = list(c.join())
|
|
clients.append(c)
|
|
return c
|
|
|
|
seated = [client("ap-seat%d" % i) for i in range(seats)]
|
|
w = client("ap-watch")
|
|
everyone = seated + [w]
|
|
check([c.seat for c in everyone] == list(range(seats)) + [OBSERVER], "%s: %d seats and a watcher (%r)" % (label, seats, [c.seat for c in everyone]))
|
|
drain_all(everyone)
|
|
for c in seated:
|
|
c.send(CTOS_UPDATE_DECK, deck_bytes([PROBE_KNIGHT] * 40))
|
|
pump(everyone, lambda: False, limit=0.8)
|
|
marks = start_duel_on(label, seated[0], everyone, None, "attack preview")
|
|
|
|
def holder_of(kind, since_marks):
|
|
return [c for c in seated if game_msgs(since(c, since_marks), kind)]
|
|
|
|
def answer(c, payload):
|
|
c.send(CTOS_TIME_CONFIRM) # the timed server holds the seat until the clock is acknowledged
|
|
c.send(CTOS_RESPONSE, payload)
|
|
|
|
def summon(stage):
|
|
# the idle holder summons its first card to the middle zone, then the prompt comes back
|
|
holders = holder_of(MSG_SELECT_IDLECMD, summon.marks)
|
|
if not check(len(holders) == 1, "%s: %s: exactly one seat holds the idle prompt (%s)" % (label, stage, [c.name for c in holders])):
|
|
return None
|
|
h = holders[0]
|
|
before = marks_of(everyone)
|
|
answer(h, struct.pack("<i", 0)) # idle command 0: summon the first summonable card
|
|
ok = pump(everyone, lambda: game_msgs(since(h, before), MSG_SELECT_PLACE), limit=6, chain=True)
|
|
if not check(ok, "%s: %s: the summon asked %s for a zone" % (label, stage, h.name)):
|
|
return None
|
|
place = game_msgs(since(h, before), MSG_SELECT_PLACE)[-1]
|
|
before = marks_of(everyone)
|
|
answer(h, bytes([place[1], MZONE, 2]))
|
|
ok = pump(everyone, lambda: game_msgs(since(h, before), MSG_SELECT_IDLECMD), limit=6, chain=True)
|
|
check(ok, "%s: %s: the knight is on the field and %s holds the idle prompt again" % (label, stage, h.name))
|
|
summon.marks = before
|
|
return h
|
|
summon.marks = marks
|
|
|
|
first = summon("turn 1")
|
|
if not first:
|
|
return
|
|
before = marks_of(everyone)
|
|
answer(first, struct.pack("<i", 7)) # idle command 7: to the End Phase
|
|
ok = pump(everyone, lambda: any(game_msgs(since(c, before), MSG_SELECT_IDLECMD) for c in seated if c is not first), limit=8, chain=True)
|
|
check(ok, "%s: turn 1 ended and the other side holds the idle prompt" % label)
|
|
summon.marks = before
|
|
second = summon("turn 2")
|
|
if not second:
|
|
return
|
|
before = marks_of(everyone)
|
|
answer(second, struct.pack("<i", 6)) # idle command 6: to the Battle Phase
|
|
ok = pump(everyone, lambda: game_msgs(since(second, before), MSG_SELECT_BATTLECMD), limit=6, chain=True)
|
|
if not check(ok, "%s: %s entered its Battle Phase and holds the battle prompt" % (label, second.name)):
|
|
return
|
|
prompt = game_msgs(since(second, before), MSG_SELECT_BATTLECMD)[-1]
|
|
n_act = prompt[2]
|
|
n_att = prompt[3 + n_act * 11]
|
|
attackers = [(prompt[4 + n_act * 11 + i * 8 + 5], prompt[4 + n_act * 11 + i * 8 + 6]) for i in range(n_att)]
|
|
check(attackers == [(MZONE, 2)], "%s: the battle prompt lists the knight at MZONE 2 as its one attacker (%s)" % (label, attackers))
|
|
other = [c for c in seated if c is not second and c is not first]
|
|
idle = other[0] if other else first # a seat whose prompt is NOT open (in Tag: a partner)
|
|
|
|
knight = (MZONE, 2, MZONE, 2)
|
|
direct = (MZONE, 2, DIRECT, 0)
|
|
not_in_prompt = (MZONE, 0, MZONE, 2)
|
|
no_such_target = (MZONE, 2, MZONE, 0)
|
|
marks2 = marks_of(everyone)
|
|
second.send(CTOS_ATTACK_PREVIEW, preview_ask([knight, direct, not_in_prompt, no_such_target]))
|
|
pump(everyone, lambda: previews(since(second, marks2)), limit=3)
|
|
got = previews(since(second, marks2))
|
|
check(len(got) == 1, "%s: the open seat's ask got exactly one ATTACK_PREVIEW (%d)" % (label, len(got)))
|
|
if got:
|
|
version, n, pairs, size = got[0]
|
|
check(version == 1 and n == 2 and size == 2 + 2 * 28, "%s: the answer is version 1, count 2, 58 bytes (%d / %d / %d)" % (label, version, n, size))
|
|
check([pr for pr, _ in pairs] == [knight, direct], "%s: the two answered pairs echo the request in order; the unlisted attacker and the empty zone are left out (%s)" % (label, [pr for pr, _ in pairs]))
|
|
if len(pairs) == 2:
|
|
check(pairs[0][1] == preview_answer(0x0C, 1800, 1800), "%s: knight into knight: both die, 1800 against 1800, no damage (%s)" % (label, pairs[0][1].hex()))
|
|
check(pairs[1][1] == preview_answer(0x20), "%s: a direct attack past a monster: illegal, every number 0 (%s)" % (label, pairs[1][1].hex()))
|
|
check(all(not previews(since(c, marks2)) for c in everyone if c is not second), "%s: nobody else got the answer" % label)
|
|
|
|
marks3 = marks_of(everyone)
|
|
idle.send(CTOS_ATTACK_PREVIEW, preview_ask([knight]))
|
|
w.send(CTOS_ATTACK_PREVIEW, preview_ask([knight]))
|
|
second.send(CTOS_ATTACK_PREVIEW, preview_ask([knight], version=2))
|
|
second.send(CTOS_ATTACK_PREVIEW, preview_ask([knight] * 65))
|
|
second.send(CTOS_ATTACK_PREVIEW, preview_ask([knight], count=2))
|
|
second.send(CTOS_ATTACK_PREVIEW, b"\x01")
|
|
pump(everyone, lambda: False, limit=1.5)
|
|
check(all(not previews(since(c, marks3)) for c in everyone), "%s: an out-of-turn ask, a watcher's ask, version 2, 65 pairs, a wrong count and a short header got no reply" % label)
|
|
alive(label, everyone, "after the dropped asks")
|
|
|
|
before = marks_of(everyone)
|
|
answer(second, struct.pack("<i", 3)) # battle command 3: to the End Phase
|
|
ok = pump(everyone, lambda: any(game_msgs(since(c, before), MSG_SELECT_IDLECMD) for c in seated if c is not second), limit=8, chain=True)
|
|
check(ok, "%s: the battle prompt still takes its real answer: the turn passed" % label)
|
|
check(all(not previews(c.log[marks[c]:]) for c in everyone if c is not second), "%s: a seat that never asks got no ATTACK_PREVIEW in the whole duel (old client unaffected)" % label)
|
|
|
|
marks4 = marks_of(everyone)
|
|
for c in seated:
|
|
if (c.seat == 0) if mode != 2 else (c.seat in (0, 1)):
|
|
c.send(CTOS_SURRENDER)
|
|
ok = pump(everyone, lambda: all(match_overs(since(c, marks4)) for c in everyone), limit=10)
|
|
check(ok, "%s: a surrender ended the match for everyone" % label)
|
|
for c in clients:
|
|
c.close()
|
|
stop_dll(dll, thread, label)
|
|
finally:
|
|
os.chdir(here)
|
|
shutil.rmtree(root, ignore_errors=True)
|
|
|
|
|
|
def attack_preview_suite(dll_path, port):
|
|
print()
|
|
print("hosting attack preview rooms from %s" % dll_path)
|
|
attack_preview_room(dll_path, port, "single", 0)
|
|
attack_preview_room(dll_path, port + 1, "tag", 2)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|