Files
yugioh-legacy-engine/contract/probe-feature-messages.py
T
donnyandClaude Opus 5.5 d31b7b62d8
Release / release (push) Successful in 9s
Release / windows (push) Successful in 33s
Release / linux (push) Successful in 1m19s
Release / android (push) Successful in 59s
Release / attach-windows (push) Successful in 1s
core: a Tag Field Spell takes the team's free Field slot (v1.7.2)
get_fzone_landing sent a Field Spell to the playing partner's slot and
replaced the card there even when the other partner's slot was free; only
a control change took the free slot. A partner who got both of the team's
Fields back with Giant Trunade and played them one after the other lost
the first. Now a Field Spell takes the free slot whenever the playing
partner's is taken; with both taken it replaces the playing partner's.

Probe: new room "tag, two in one turn" (seq 5 then 6 on turn 1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WoiqG2TqZQmJ8tTn8tYpgy
2026-11-12 14:54:23 -07:00

3968 lines
211 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
# 27961) 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 (Tag: the fourth duelist on turn 4, since
# v1.1.1 allows no Battle Phase on tag turns 1-3); 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.
#
# With --dll it also gates v1.2.0 (TICKET-405, tag partner cards): the server's
# capability said protocol 9 + flag 0x2000 (single and tag; 10 / 0x1000 since v1.5.0); in a Tag room each
# seat gets TAG_PARTNER_CARDS (0x5F: side, version 1, hand count, extra count,
# pad, u16 deck count, then the hand, Extra Deck and deck codes) for its own side
# only -- at the start the waiting member's 5-card opening hand, its two Probe
# Fusions and its 35 remaining cards SORTED; after each MSG_TAG_SWAP the member
# that just left, hand = every card it drew, deck = its deck minus them; a seat's
# field resync (CTOS_REQUEST_FIELD) carries the same list again to that seat
# alone -- and the other team never gets one. The hand a swap brings in is the
# hand the opening 0x5F announced. TICKET-412: when the room shows all, the
# watcher gets the same bytes for BOTH sides at every send point, its resync and
# a late watcher's snapshot carry both sides; with ygol.room.spectatorview=hidden
# the watcher, its resync and the late watcher's snapshot never get one.
#
# With --dll it also gates v1.4.0 (life points per side): two more setup-pair
# rooms (Single and Tag) with ygol.side.b.lp=4000 start a duel; every seat's
# MSG_START carries 8000 for seat side A and 4000 for side B in DUEL PLAYER
# order (the side that goes first is player 0, so the two values swap when
# side B won the toss), and the replay has flag 0x20000000 with the same two
# values after opt. Every other room's replay has no such flag.
#
# With --dll it also gates v1.4.2 (TICKET-424, tag partner cards on change): in
# the TICKET-415 room the Fusion seat 3 picked leaves seat 3's Extra Deck in
# seat 2's Standby Phase of turn 6, while seat 3 waits; between that
# MSG_SPSUMMONING and the next MSG_TAG_SWAP seats 2 and 3 get exactly one
# TAG_PARTNER_CARDS, for side 1 with an empty Extra Deck, and seats 0 and 1 none.
#
# With --dll it also gates v1.5.0 (proposal 45 / TICKET-384, Tag two Field slots):
# the capability says protocol 10 + flag 0x1000 (single and tag); a Tag room
# refuses a joiner whose CTOS_CAPABILITY lacks 0x1000 (ERROR_MSG VERERROR, then
# disconnected) and keeps one that has it, a Single room keeps both; in a Tag room
# seat 0's Field Spell lands in Spell/Trap sequence 5 on turn 1, seat 1's in
# sequence 6 on turn 3 while the first stays, and seat 0's next Field on turn 5
# sends only the sequence-5 card to the Graveyard. The Field's own script reports
# in a HINT what the core sees: LOCATION_FZONE counts both slots,
# Duel.GetFieldCard(tp, LOCATION_FZONE, 0) is the playing partner's field and 1
# the other, Duel.IsEnvironment and Card.IsLocation see sequence 6.
#
# With --dll it also gates v1.6.0 (proposal 53 / TICKET-433, Tag shared Extra Deck):
# the capability says protocol 11 + flag 0x4000 (single and tag); a Tag room
# refuses a joiner whose CTOS_CAPABILITY lacks 0x4000, a Single room keeps it. With
# ygol.tag.extra=shared MSG_START carries the sum of both partners' Extra Decks,
# the opening Extra Deck refresh lists all of them with QUERY_TAG_MEMBER 0x1000000
# (0 from seat 0 / 2, 1 from seat 1 / 3; the other team's masked copy has flag 0),
# 0x5F reports an Extra count of 0, seat 0 Summons seat 1's monster on turn 1,
# seat 1 returns it on turn 3, and the value is still 1 in the refresh after the
# swap of turn 5; a late watcher's snapshot refresh has the values; no
# other query carries the bit; the replay has option 0x200 and plays back through
# the library to the same Summons. Without the pair the partners' lists stay
# apart and no query carries the bit.
#
# With --dll it also gates v1.7.0 (proposal 55 / TICKET-451, prompt context): the capability says protocol 12 +
# flag 0x8000 (single and tag) and no room refuses a joiner without it. A card (Probe Ask) registers two effects
# that never run, then an Activate that asks a yes/no in its cost, an option in its target and a yes/no in its
# operation, runs a Fusion Monster's material procedure (which asks) inside that operation and asks again, shuffles
# itself into the deck and asks the opponent, then its controller. Every prompt a seat with
# 0x8000 gets comes right after one 24-byte PROMPT_CONTEXT (0x44) naming that prompt: idle, chain and battle
# prompts say no effect; cost / target / operation say Probe Ask, phase 1 / 2 / 3, effect index 2, its
# description, chain link 1; the nested procedure names the Fusion (index 1, chain link 0) and the operation's
# next prompt names Probe Ask again; an announce says kind 0 (plain), 1 (Duel.AnnounceLevel) or 2 (a dice effect);
# the Fusion's optional End Phase trigger is asked with phase 4 (ask), index 2;
# the opponent's yes/no names the card in the deck as hidden (code 0, index 0xFFFF,
# description 0) while its controller's next one still names it. A watcher with 0x8000, a seat without it and
# the waiting Tag partners get none; a second duel with another deck order reports the same indexes.
#
# 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 == 12 and flags == 0xF7FF, "%s: server capability is protocol 12, flags 0xF7FF (appearance | dialogue | setup pairs | seat plan | rules restart | seat state | lobby after match | coin toss | deck lists | profile | attack preview | tag two fields | tag partner cards | tag shared extra | prompt context), 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? a port inside the OS dynamic range collides with the probe's own connections)" % 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()
# Above every OS dynamic (ephemeral) port range: this machine hands outgoing connections ports
# 1024-15000 (netsh int ipv4 show dynamicport tcp), and a probe client that drew the next room's
# port made that room's bind fail ("0", then "ended before it listened") on most runs.
port = o.port or (27961 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)
tag_partner_suite(o.dll, port + 110)
tag_across_swap_suite(o.dll, port + 120)
tag_two_fields_suite(o.dll, port + 130)
tag_shared_extra_suite(o.dll, port + 140)
prompt_context_suite(o.dll, port + 150)
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
REPLAY_YGOL_SIDE_LP = 0x20000000
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; the cwd is the Unity
# repo root (every --dll run requires that already), so Data/script.zip is read from there
repo = os.getcwd()
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,))
# v1.2.0 (TICKET-405): a Fusion monster, so a submitted deck has an Extra Deck
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 65, 2000, 2000, 6, 1, 16, 0)", (PROBE_FUSION,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Fusion', ''" + ", ''" * 16 + ")", (PROBE_FUSION,))
# TICKET-415: a Spell that keeps a card across the tag swap (its script is read from ./script)
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 2, 0, 0, 0, 0, 0, 0)", (PROBE_TIME_FUSION,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Time Fusion', ''" + ", ''" * 16 + ")", (PROBE_TIME_FUSION,))
db.commit()
db.close()
with open(os.path.join(root, "script", "c%d.lua" % PROBE_TIME_FUSION), "w", newline="\n") as f:
f.write(TIME_FUSION_LUA)
# proposal 45 (TICKET-384): a Field Spell, so a Tag team can hold one per partner
db = sqlite3.connect(os.path.join(root, "cards.cdb"))
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 524290, 0, 0, 0, 0, 0, 0)", (PROBE_FIELD,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Field', ''" + ", ''" * 16 + ")", (PROBE_FIELD,))
db.commit()
db.close()
with open(os.path.join(root, "script", "c%d.lua" % PROBE_FIELD), "w", newline="\n") as f:
f.write(FIELD_LUA)
# proposal 53 (TICKET-433): a Fusion per seat and a Spell that Summons one or returns it
db = sqlite3.connect(os.path.join(root, "cards.cdb"))
for i, code in enumerate(PROBE_SEAT_FUSIONS):
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 65, 2000, 2000, 6, 1, 16, 0)", (code,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Seat Fusion %d', ''" % i + ", ''" * 16 + ")", (code,))
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 2, 0, 0, 0, 0, 0, 0)", (PROBE_EXTRA_SPELL,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Extra Spell', ''" + ", ''" * 16 + ")", (PROBE_EXTRA_SPELL,))
db.commit()
db.close()
with open(os.path.join(root, "script", "c%d.lua" % PROBE_EXTRA_SPELL), "w", newline="\n") as f:
f.write(EXTRA_SPELL_LUA)
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, lp=None):
reps = replays(c)
if not check(len(reps) >= 1, "%s: a REPLAY arrived at duel end" % who):
return
flag, seeds, body = reps[-1]
seats = 4 if tag else 2
lp_at = (4 + struct.unpack_from("<I", body, 0)[0] if pairs else 0) + 40 * seats + 16
if lp is not None:
if check(flag & REPLAY_YGOL_SIDE_LP, "%s: replay flag has the side LP bit 0x20000000 (flag 0x%x)" % (who, flag)):
got = struct.unpack_from("<ii", body, lp_at)
check(got == tuple(lp), "%s: replay carries int32 lp[0], lp[1] after opt in duel player order %s (got %s)" % (who, tuple(lp), got))
else:
check(not flag & REPLAY_YGOL_SIDE_LP, "%s: replay flag has NO side LP bit (flag 0x%x)" % (who, flag))
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 starts_of(c):
return [d for p, d in c.log if p == 0x01 and len(d) >= 11 and d[0] == MSG_START]
def check_side_lp(label, clients, lp):
# lp = (side A, side B) by SEAT side; MSG_START lists duel players, and the side that goes first is player 0
duel_lp = None
for c in clients:
side = 1 if c.seat >= 2 else (1 if c.seat == 1 and len(clients) == 2 else 0)
got = starts_of(c)
if not check(len(got) == 1, "%s: seat %d got one MSG_START (got %d)" % (label, c.seat, len(got))):
continue
player = got[0][1] & 0xF
want = tuple(lp) if player == side else (lp[1], lp[0])
pair = struct.unpack_from("<ii", got[0], 3)
check(pair == want, "%s: seat %d (duel player %d) MSG_START lp = %s in duel player order (got %s)" % (label, c.seat, player, want, pair))
duel_lp = duel_lp or pair
return duel_lp
def run_case(dll_path, root, port, label, pairs, mode=0, seed_tag=None, junk=(), watcher=False, lp=None):
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)
duel_lp = None
if lp is not None:
pump(clients, lambda: all(starts_of(c) for c in clients), limit=5, hand=hand)
duel_lp = check_side_lp(label, clients, lp)
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), lp=duel_lp)
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)
run_case(dll_path, root, port + 5, "side b lp", ["ygol.side.b.lp=4000"], lp=(8000, 4000))
run_case(dll_path, root, port + 6, "side b lp tag", ["ygol.side.b.lp=4000"], mode=2, lp=(8000, 4000))
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 | FEATURE_TAG_TWO_FIELDS | FEATURE_TAG_SHARED_EXTRA)) # a Tag room refuses a client without 0x1000 (proposal 45) or 0x4000 (proposal 53)
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 %s Battle Phase)" % (label, seats, "fourth duelist's turn-4" if mode == 2 else "second seat's"))
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
if mode == 2:
# v1.1.1: a Tag duel has no Battle Phase on turns 1-3; the fourth duelist (2B) is the first who may battle
for stage in ("turn 3", "turn 4"):
before = marks_of(everyone)
answer(second, 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 second), limit=8, chain=True)
holders = [c for c in seated if game_msgs(since(c, before), MSG_SELECT_IDLECMD)]
if not check(ok and len(holders) == 1, "%s: %s: the turn passed and one swapped-in seat holds the idle prompt (%s)" % (label, stage, [c.name for c in holders])):
return
second = holders[0]
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)
# --- v1.2.0 (TICKET-405): tag partner cards --------------------------------------
STOC_TAG_PARTNER_CARDS, CTOS_REQUEST_FIELD, MSG_RELOAD_FIELD = 0x5F, 0x30, 162
NAMES.update({0x5F: "TAG_PARTNER_CARDS"})
PROBE_FUSION = PROBE_CARD + 600 # a Fusion monster: it goes to the Extra Deck
TAG_PARTNER_DECKS = [DECK_LIST_CODES[seat] + [PROBE_FUSION, PROBE_FUSION] for seat in range(4)]
def partner_cards(pkts, side=None):
# (side, version, hand, extra, deck, size); hand / extra / deck are None when the size does not match the counts
out = []
for p, d in pkts:
if p != STOC_TAG_PARTNER_CARDS or len(d) < 7:
continue
s, version, hand_n, extra_n, _pad, deck_n = struct.unpack_from("<BBBBBH", d, 0)
if side is not None and s != side:
continue
n = hand_n + extra_n + deck_n
if len(d) != 7 + 4 * n:
out.append((s, version, None, None, None, len(d)))
continue
codes = list(struct.unpack_from("<%dI" % n, d, 7))
out.append((s, version, codes[:hand_n], codes[hand_n:hand_n + extra_n], codes[hand_n + extra_n:], len(d)))
return out
def server_capability(pkts):
for p, d in pkts:
if p == STOC_CAPABILITY and len(d) == 8 and struct.unpack_from("<H", d, 0)[0] == SERVER:
return struct.unpack_from("<HI", d, 2)
return None
def tag_swap_hand(d):
# MSG_TAG_SWAP: player, main count, extra count, pendulum count, hand count, u32 top, u32 x hand, u32 x extra
hcount = d[5]
return [c & 0x7FFFFFFF for c in struct.unpack_from("<%dI" % hcount, d, 10)]
def tag_partner_room(dll_path, port, label, hidden):
print("== tag partner cards, %s (4 seats + a watcher: the opening hands, both swaps, a seat's and the watcher's field resync, a late watcher)" % label)
root = make_workspace()
here = os.getcwd()
os.chdir(root)
try:
write_special(root, [])
dll, thread = host_dll(dll_path, port, 2, 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("tp-seat%d" % i) for i in range(4)]
w = client("tp-watch")
everyone = seated + [w]
check([c.seat for c in everyone] == [0, 1, 2, 3, OBSERVER], "%s: four seats and a watcher (%r)" % (label, [c.seat for c in everyone]))
cap = server_capability(seated[0].log)
check(cap == (12, 0xF7FF), "%s: the tag server's capability is protocol 12, flags 0xF7FF (got %s)" % (label, cap))
drain_all(everyone)
for c in seated:
c.send(CTOS_UPDATE_DECK, deck_bytes(TAG_PARTNER_DECKS[c.seat]))
pump(everyone, lambda: False, limit=0.8)
marks = start_duel_on(label, seated[0], everyone, None, "tag partner cards")
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" % label)
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]) == 2 for p in (0, 1)), "%s: every seat got one MSG_START naming its side (%s)" % (label, {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)}
extra_expected = [PROBE_FUSION, PROBE_FUSION]
def check_cards(side, since_marks, stage, waiting_seat, expect_hand=None):
pool = set(DECK_LIST_CODES[waiting_seat])
latest = None
for c in by_side[side]:
got = partner_cards(since(c, since_marks), side)
check(len(got) == 1, "%s: %s: seat %d got exactly one TAG_PARTNER_CARDS for its side %d (%d)" % (label, stage, c.seat, side, len(got)))
check(not partner_cards(since(c, since_marks), 1 - side), "%s: %s: seat %d got none for the other side" % (label, stage, c.seat))
if not got:
continue
s, version, hand, extra, deck, size = got[-1]
if not check(hand is not None, "%s: %s: seat %d's TAG_PARTNER_CARDS is 7 + 4 x counts bytes (%d)" % (label, stage, c.seat, size)):
continue
check(version == 1, "%s: %s: seat %d's list is version 1 (%d)" % (label, stage, c.seat, version))
if expect_hand is None:
check(len(hand) == 5 and set(hand) <= pool, "%s: %s: seat %d's partner hand is 5 cards of seat %d's deck (%s)" % (label, stage, c.seat, waiting_seat, hand))
else:
check(sorted(hand) == sorted(expect_hand), "%s: %s: seat %d's partner hand is every card seat %d drew (%d; expected %d)" % (label, stage, c.seat, waiting_seat, len(hand), len(expect_hand)))
check(extra == extra_expected, "%s: %s: seat %d's partner Extra Deck is the two Probe Fusions, face-down (%s)" % (label, stage, c.seat, extra))
check(deck == sorted(deck) and len(deck) == len(set(deck)), "%s: %s: seat %d's partner deck is sorted ascending" % (label, stage, c.seat))
check(deck == sorted(pool - set(hand)), "%s: %s: seat %d's partner deck is seat %d's Main Deck minus the hand (%d)" % (label, stage, c.seat, waiting_seat, len(deck)))
latest = got[-1]
for c in by_side[1 - side]:
check(not partner_cards(since(c, since_marks), side), "%s: %s: seat %d (the other team) got no TAG_PARTNER_CARDS for side %d" % (label, stage, c.seat, side))
check_watcher(w, since_marks, stage, side, latest)
return latest
def check_watcher(c, since_marks, stage, side, latest):
if hidden:
check(not partner_cards(since(c, since_marks)), "%s: %s: %s got no TAG_PARTNER_CARDS (hidden)" % (label, stage, c.name))
return
got = partner_cards(since(c, since_marks), side)
check(len(got) == 1, "%s: %s: %s got exactly one TAG_PARTNER_CARDS for side %d (%d)" % (label, stage, c.name, side, len(got)))
check(bool(got) and bool(latest) and got[-1][1:5] == latest[1:5], "%s: %s: %s's side %d list is the bytes the seats got" % (label, stage, c.name, side))
opening = {}
for p in (0, 1):
opening[p] = check_cards(p, marks, "opening", partner_seat[p])
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)" % (label, 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 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" % (label, stage))
end_turn.marks = before
return before
end_turn.marks = marks
def check_swap(side, before, stage):
owner = by_side[side][0]
new = since(owner, before)
cut = next((i for i, (pid, _) in enumerate(new) if pid == STOC_TAG_PARTNER_CARDS), None)
if not check(cut is not None, "%s: %s: side %d got a TAG_PARTNER_CARDS after its swap" % (label, stage, side)):
return
pre = owner.log[marks[owner]:before[owner] + cut]
drawn = [x for d in draws(pre, side) for x in draw_codes(d)]
check(len(drawn) >= 5, "%s: %s: seat %d drew %d cards before the swap" % (label, stage, first_seat[side], len(drawn)))
check_cards(side, before, stage, first_seat[side], expect_hand=drawn)
check(not partner_cards(since(w, before), 1 - side), "%s: %s: the watcher got none for the other side" % (label, stage))
swaps = [d for d in game_msgs(new, MSG_TAG_SWAP) if len(d) > 10 and d[1] == side]
check(len(swaps) == 1, "%s: %s: side %d saw one MSG_TAG_SWAP for itself (%d)" % (label, stage, side, len(swaps)))
if swaps and opening.get(side) and opening[side][2] is not None:
check(sorted(tag_swap_hand(swaps[0])) == sorted(opening[side][2]), "%s: %s: the hand the swap brought in is the hand the opening TAG_PARTNER_CARDS announced" % (label, stage))
before = end_turn("pass 1") # turn 2: side 1's first turn, no swap
if before:
check(all(not partner_cards(since(c, before)) for c in everyone), "%s: pass 1: a turn without a swap sent nobody a TAG_PARTNER_CARDS" % label)
before = end_turn("pass 2") # turn 3: side 0 swaps to its partner
if before:
check_swap(0, before, "pass 2")
before = end_turn("pass 3") # turn 4: side 1 swaps to its partner
if before:
check_swap(1, before, "pass 3")
asker = by_side[0][1]
last = {p: partner_cards(by_side[p][0].log[marks[by_side[p][0]]:], p) for p in (0, 1)}
marks3 = marks_of(everyone)
asker.send(CTOS_REQUEST_FIELD)
w.send(CTOS_REQUEST_FIELD)
pump(everyone, lambda: partner_cards(since(asker, marks3)) and game_msgs(since(w, marks3), MSG_RELOAD_FIELD) and (hidden or len(partner_cards(since(w, marks3))) >= 2), limit=3)
got = partner_cards(since(asker, marks3), 0)
check(len(got) == 1 and bool(game_msgs(since(asker, marks3), MSG_RELOAD_FIELD)), "%s: a seat's field resync carried one TAG_PARTNER_CARDS for its side (%d)" % (label, len(got)))
check(bool(got) and bool(last[0]) and got[0][2:5] == last[0][-1][2:5], "%s: the resync list equals the last list that seat got" % label)
check(bool(game_msgs(since(w, marks3), MSG_RELOAD_FIELD)) and all(not partner_cards(since(c, marks3)) for c in everyone if c is not asker and c is not w), "%s: the watcher's resync reloaded its field and the other seats got no TAG_PARTNER_CARDS" % label)
for p in (0, 1):
check_watcher(w, marks3, "watcher resync", p, last[p][-1] if last[p] else None)
l = client("tp-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" % label)
late_marks = {l: 0}
for p in (0, 1):
check_watcher(l, late_marks, "late snapshot", p, last[p][-1] if last[p] else None)
marks4 = marks_of(everyone + [l])
for c in by_side[0]:
c.send(CTOS_SURRENDER)
ok = pump(everyone + [l], lambda: all(match_overs(since(c, marks4)) for c in everyone + [l]), limit=10)
check(ok, "%s: side 0 surrendered: MATCH_OVER reached everyone" % label)
for c in clients:
c.close()
stop_dll(dll, thread, label)
finally:
os.chdir(here)
shutil.rmtree(root, ignore_errors=True)
def tag_partner_suite(dll_path, port):
print()
print("hosting the tag partner cards rooms from %s" % dll_path)
tag_partner_room(dll_path, port, "tag, see all", hidden=False)
tag_partner_room(dll_path, port + 1, "tag, hidden", hidden=True)
# --- TICKET-415: a card the waiting tag partner holds --------------------------------------------
# Time Fusion picks a Fusion from the Extra Deck and Summons it at the team's next Standby Phase. By
# then the partners have swapped: the Fusion sits in the waiting partner's tag_list_extra, and the core
# erased the ACTIVE Extra Deck at its sequence (past the end of an empty one: the Editor crash of
# 2026-10-16). The fixed core takes the card out of the list that holds it.
PROBE_TIME_FUSION = PROBE_CARD + 700
MSG_RETRY, MSG_SELECT_CARD, MSG_SELECT_POSITION, MSG_SPSUMMONING, MSG_NEW_TURN = 1, 15, 19, 62, 40
MSG_SELECT_EFFECTYN, MSG_SELECT_YESNO, MSG_SELECT_OPTION, MSG_SELECT_DISFIELD, MSG_SELECT_TRIBUTE = 12, 13, 14, 24, 20
TIME_FUSION_LUA = """--Probe Time Fusion (TICKET-415): banish 1 other card from the hand; pick 1 Fusion Monster in the Extra Deck.
--During the next Standby Phase of the player who activated this: Special Summon that Fusion Monster.
local s,id,o=GetID()
function s.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(s.cost)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.costfilter(c)
return c:IsAbleToRemoveAsCost()
end
function s.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.costfilter,tp,LOCATION_HAND,0,1,e:GetHandler()) end
local g=Duel.SelectMatchingCard(tp,s.costfilter,tp,LOCATION_HAND,0,1,1,e:GetHandler())
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function s.ffilter(c)
return c:IsType(TYPE_FUSION)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.ffilter,tp,LOCATION_EXTRA,0,1,nil) end
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.SelectMatchingCard(tp,s.ffilter,tp,LOCATION_EXTRA,0,1,1,nil):GetFirst()
if not tc then return end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetLabelObject(tc)
e1:SetCondition(s.spcon)
e1:SetOperation(s.spop)
e1:SetReset(RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN)
Duel.RegisterEffect(e1,tp)
end
function s.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function s.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
if tc:IsLocation(LOCATION_EXTRA) then
Duel.SpecialSummon(tc,0,tp,tp,true,false,POS_FACEUP)
end
end
"""
def first_free_zone(d):
# MSG_SELECT_PLACE / DISFIELD: player, min, u32 flag (a set bit = that zone is NOT available)
player = d[1]
(flag,) = struct.unpack_from("<I", d, 3)
for side in (0, 1):
for seq in range(7):
if not flag & (1 << (side * 16 + seq)):
return bytes([player if side == 0 else 1 - player, 0x04, seq])
for seq in range(8):
if not flag & (1 << (side * 16 + 8 + seq)):
return bytes([player if side == 0 else 1 - player, 0x08, seq])
return bytes([player, 0x04, 0])
def tag_across_swap_room(dll_path, port, label):
print("== tag card across the swap, %s (TICKET-415: seat 3 picks its Fusion on turn 4; the team's next Standby Phase is seat 2's turn 6, whose Extra Deck is empty)" % label)
root = make_workspace()
here = os.getcwd()
os.chdir(root)
try:
write_special(root, [])
dll, thread = host_dll(dll_path, port, 2)
seated = []
for i in range(4):
c = Client("127.0.0.1", port, "ts-seat%d" % i)
c.log = list(c.join())
seated.append(c)
check([c.seat for c in seated] == [0, 1, 2, 3], "%s: four seats (%r)" % (label, [c.seat for c in seated]))
drain_all(seated)
decks = {0: [PROBE_CARD] * 40, 1: [PROBE_CARD] * 40, 2: [PROBE_CARD] * 40, 3: [PROBE_TIME_FUSION] * 40 + [PROBE_FUSION]}
for c in seated:
c.send(CTOS_UPDATE_DECK, deck_bytes(decks[c.seat]))
pump(seated, lambda: False, limit=0.8)
seated[0].send(CTOS_HS_START)
state = {"turn": 0, "activated": False, "retries": 0, "summoned": [], "idle_after_summon": 0, "swap8": None}
def answer(c, payload):
c.send(CTOS_TIME_CONFIRM)
c.send(CTOS_RESPONSE, payload)
def play(until, limit):
deadline = time.time() + limit
while time.time() < deadline:
for c in seated:
for pid, d in c.drain(quiet=0.02, limit=0.2):
c.log.append((pid, d))
if pid == STOC_SELECT_TP:
c.send(CTOS_TP_RESULT, bytes([1 if c.seat == 0 else 0])) # side A (seats 0 + 1) goes first
continue
if pid != 0x01 or not d:
continue
t = d[0]
if t == MSG_NEW_TURN and c.seat == 0:
state["turn"] += 1
elif t == MSG_TAG_SWAP and c.seat == 2 and d[1] == 1 and state["turn"] == 8:
state["swap8"] = d
elif t == MSG_SPSUMMONING and c.seat == 2:
state["summoned"].append((state["turn"], struct.unpack_from("<I", d, 1)[0]))
elif t == MSG_RETRY:
state["retries"] += 1
elif t == MSG_SELECT_IDLECMD:
n = 2
for k in range(5):
n += 1 + d[n] * 7
activatable = d[n]
if c.seat == 3 and activatable and not state["activated"]:
state["activated"] = state["turn"]
answer(c, struct.pack("<i", 5)) # activate the first card: the Spell
else:
if c.seat == 2 and state["summoned"]:
state["idle_after_summon"] += 1
answer(c, struct.pack("<i", 7)) # to the End Phase
elif t in (MSG_SELECT_CARD, MSG_SELECT_TRIBUTE):
answer(c, bytes([1, 0]))
elif t == MSG_SELECT_CHAIN:
answer(c, struct.pack("<i", -1))
elif t in (MSG_SELECT_PLACE, MSG_SELECT_DISFIELD):
answer(c, first_free_zone(d))
elif t == MSG_SELECT_POSITION:
answer(c, struct.pack("<i", next(b for b in (1, 2, 4, 8) if d[6] & b)))
elif t in (MSG_SELECT_EFFECTYN, MSG_SELECT_YESNO):
answer(c, struct.pack("<i", 1))
elif t in (MSG_SELECT_OPTION, MSG_SELECT_BATTLECMD):
answer(c, struct.pack("<i", 0 if t == MSG_SELECT_OPTION else 3))
if until():
return True
if any(c.closed for c in seated):
return False
return until()
ok = play(lambda: state["turn"] >= 6 and state["idle_after_summon"] >= 1, limit=40)
check(state["activated"] == 4, "%s: seat 3 activated the Spell on turn 4, its first turn (turn %s)" % (label, state["activated"]))
check(ok, "%s: turn 6 (seat 2's second turn) played on: the engine survived the Standby Phase" % label)
check(state["summoned"] == [(6, PROBE_FUSION)], "%s: the Fusion seat 3 picked was Special Summoned in seat 2's Standby Phase of turn 6, out of the waiting partner's Extra Deck (%s)" % (label, state["summoned"]))
check(state["retries"] == 0, "%s: no answer was refused (MSG_RETRY x%d)" % (label, state["retries"]))
ok = play(lambda: state["swap8"] is not None, limit=20)
check(ok and state["swap8"] is not None and state["swap8"][3] == 0, "%s: the swap of turn 8 brings seat 3 back with an empty Extra Deck: the Fusion left the list that held it (%s)" % (label, None if state["swap8"] is None else state["swap8"][3]))
for c in seated:
# TICKET-424: the waiting member's Extra Deck changed mid-turn, so its side's seats get the new bytes once
log = c.log
start = next((i for i, (p, d) in enumerate(log) if p == 0x01 and d and d[0] == MSG_SPSUMMONING and struct.unpack_from("<I", d, 1)[0] == PROBE_FUSION), None)
if not check(start is not None, "%s: seat %d saw the Fusion's MSG_SPSUMMONING" % (label, c.seat)):
continue
end = next((i for i in range(start + 1, len(log)) if log[i][0] == 0x01 and log[i][1] and log[i][1][0] == MSG_TAG_SWAP), len(log))
got = partner_cards(log[start + 1:end])
if c.seat >= 2:
check(len(got) == 1 and got[0][0] == 1 and got[0][3] == [], "%s: seat %d got exactly one TAG_PARTNER_CARDS after the Summon out of the waiting partner's Extra Deck, side 1 with an empty Extra Deck (%s)" % (label, c.seat, [(g[0], g[3]) for g in got]))
else:
check(not got, "%s: seat %d (the other team) got no TAG_PARTNER_CARDS for the change (%d)" % (label, c.seat, len(got)))
check(all(not c.closed for c in seated), "%s: every seat is still connected" % label)
marks = marks_of(seated)
for c in seated[:2]:
c.send(CTOS_SURRENDER)
ok = pump(seated, lambda: all(match_overs(since(c, marks)) for c in seated), limit=10)
check(ok, "%s: side 0 surrendered: MATCH_OVER reached everyone" % label)
for c in seated:
c.close()
stop_dll(dll, thread, label)
finally:
os.chdir(here)
shutil.rmtree(root, ignore_errors=True)
def tag_across_swap_suite(dll_path, port):
print()
print("hosting the tag card across the swap room from %s" % dll_path)
tag_across_swap_room(dll_path, port, "tag")
# --- proposal 45 (TICKET-384): Tag two Field slots ---------------------------------------------
# In Tag on Master Rule 4/5 each partner has a Field slot: Spell/Trap sequence 5 for the partner
# who plays the team's first turn, 6 for the other. A Field Spell lands in the playing partner's
# slot and replaces only that slot; LOCATION_FZONE covers both. Capability 0x1000, protocol 10; a
# Tag room refuses a client whose capability lacks the bit, a Single room does not care.
FEATURE_TAG_TWO_FIELDS = 0x1000
PROBE_FIELD = PROBE_CARD + 800
MSG_MOVE, MSG_HINT, HINT_CARD, LOCATION_SZONE, LOCATION_GRAVE = 50, 2, 10, 0x08, 0x10
STOC_ERROR_MSG, ERRMSG_VERERROR = 0x02, 0x4
FIELD_LUA = """--Probe Field (proposal 45): a Field Spell with no effect of its own. On activation it reports what the core
--sees of its team's Field Zone in one MSG_HINT (HINT_CARD): bits 0-3 = Duel.GetFieldGroupCount(tp, LOCATION_FZONE),
--0x10 GetFieldCard(FZONE, 0) exists, 0x20 GetFieldCard(FZONE, 1) exists, 0x40 IsEnvironment, 0x80 IsLocation(FZONE),
--0x100 GetFieldCard(FZONE, 0) is this card, 0x200 CheckLocation(FZONE, 1), bits 12+ = this card's sequence.
local s,id,o=GetID()
function s.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local f0=Duel.GetFieldCard(tp,LOCATION_FZONE,0)
local f1=Duel.GetFieldCard(tp,LOCATION_FZONE,1)
local v=Duel.GetFieldGroupCount(tp,LOCATION_FZONE,0)
if f0 then v=v+0x10 end
if f1 then v=v+0x20 end
if Duel.IsEnvironment(id,tp,LOCATION_FZONE) then v=v+0x40 end
if c:IsLocation(LOCATION_FZONE) then v=v+0x80 end
if f0==c then v=v+0x100 end
if Duel.CheckLocation(tp,LOCATION_FZONE,1) then v=v+0x200 end
v=v+c:GetSequence()*0x1000
Duel.Hint(10,tp,v)
end
"""
def info_location(v):
return (v & 0xFF, (v >> 8) & 0xFF, (v >> 16) & 0xFF)
def field_hints(pkts):
return [struct.unpack_from("<I", d, 3)[0] for p, d in pkts if p == 0x01 and len(d) >= 7 and d[0] == MSG_HINT and d[1] == HINT_CARD]
def error_msgs(pkts):
return [d[0] for p, d in pkts if p == STOC_ERROR_MSG and d]
def tag_two_fields_room(dll_path, port, label, first_turn_fields=1):
if first_turn_fields == 1:
print("== tag two Field slots, %s (seat 0 plays a Field on turn 1, seat 1 on turn 3, seat 0 again on turn 5)" % label)
else:
print("== tag two Field slots, %s (seat 0 plays two Fields on turn 1, seat 1 one on turn 3, seat 0 one on turn 5)" % label)
root = make_workspace()
here = os.getcwd()
os.chdir(root)
try:
write_special(root, [])
dll, thread = host_dll(dll_path, port, 2)
seated = []
for i in range(4):
c = Client("127.0.0.1", port, "tf-seat%d" % i)
c.log = list(c.join())
seated.append(c)
check([c.seat for c in seated] == [0, 1, 2, 3], "%s: four seats (%r)" % (label, [c.seat for c in seated]))
cap = server_capability(seated[0].log)
check(cap == (12, 0xF7FF), "%s: the tag server's capability is protocol 12, flags 0xF7FF (got %s)" % (label, cap))
drain_all(seated)
old = Client("127.0.0.1", port, "tf-old")
old.log = list(old.join())
old.send(CTOS_CAPABILITY, capability_bytes(9, 0x27FF))
old.log += old.drain(quiet=0.4)
check(old.seat == OBSERVER and error_msgs(old.log) == [ERRMSG_VERERROR] and old.closed,
"%s: a joiner whose capability lacks 0x1000 gets ERROR_MSG VERERROR and is disconnected (seat %r, errors %r, closed %r)" % (label, old.seat, error_msgs(old.log), old.closed))
new = Client("127.0.0.1", port, "tf-new")
new.log = list(new.join())
new.send(CTOS_CAPABILITY, capability_bytes(11, 0x77FB))
new.log += new.drain(quiet=0.4)
check(new.seat == OBSERVER and not error_msgs(new.log) and not new.closed and stamped(new.log, STOC_CAPABILITY, OBSERVER) == [capability_bytes(11, 0x77FB)],
"%s: a joiner with 0x1000 and 0x4000 stays and its CAPABILITY is relayed (errors %r, closed %r)" % (label, error_msgs(new.log), new.closed))
new.close()
drain_all(seated)
decks = {0: [PROBE_FIELD] * 40, 1: [PROBE_FIELD] * 40, 2: [PROBE_CARD] * 40, 3: [PROBE_CARD] * 40}
for c in seated:
c.send(CTOS_UPDATE_DECK, deck_bytes(decks[c.seat]))
pump(seated, lambda: False, limit=0.8)
seated[0].send(CTOS_HS_START)
state = {"turn": 0, "acted": {}, "retries": 0, "moves": []}
def answer(c, payload):
c.send(CTOS_TIME_CONFIRM)
c.send(CTOS_RESPONSE, payload)
def play(until, limit):
deadline = time.time() + limit
while time.time() < deadline:
for c in seated:
for pid, d in c.drain(quiet=0.02, limit=0.2):
c.log.append((pid, d))
if pid == STOC_SELECT_TP:
c.send(CTOS_TP_RESULT, bytes([1 if c.seat == 0 else 0])) # side A (seats 0 + 1) goes first
continue
if pid != 0x01 or not d:
continue
t = d[0]
if t == MSG_NEW_TURN and c.seat == 0:
state["turn"] += 1
elif t == MSG_MOVE and c.seat == 0 and len(d) >= 17:
code, prev, cur, _reason = struct.unpack_from("<IIII", d, 1)
state["moves"].append((state["turn"], code, info_location(prev), info_location(cur)))
elif t == MSG_RETRY:
state["retries"] += 1
elif t == MSG_SELECT_IDLECMD:
n = 2
for k in range(5):
n += 1 + d[n] * 7
activatable = d[n]
allowed = first_turn_fields if state["turn"] == 1 else 1
if activatable and state["acted"].get(state["turn"], 0) < allowed:
state["acted"][state["turn"]] = state["acted"].get(state["turn"], 0) + 1
answer(c, struct.pack("<i", 5)) # activate the first card: a Probe Field
else:
answer(c, struct.pack("<i", 7)) # to the End Phase
elif t in (MSG_SELECT_CARD, MSG_SELECT_TRIBUTE):
answer(c, bytes([1, 0]))
elif t == MSG_SELECT_CHAIN:
answer(c, struct.pack("<i", -1))
elif t in (MSG_SELECT_PLACE, MSG_SELECT_DISFIELD):
answer(c, first_free_zone(d))
elif t == MSG_SELECT_POSITION:
answer(c, struct.pack("<i", next(b for b in (1, 2, 4, 8) if d[6] & b)))
elif t in (MSG_SELECT_EFFECTYN, MSG_SELECT_YESNO):
answer(c, struct.pack("<i", 1))
elif t in (MSG_SELECT_OPTION, MSG_SELECT_BATTLECMD):
answer(c, struct.pack("<i", 0 if t == MSG_SELECT_OPTION else 3))
if until():
return True
if any(c.closed for c in seated):
return False
return until()
ok = play(lambda: state["turn"] >= 6, limit=40)
check(ok, "%s: the duel reached turn 6 (turn %d)" % (label, state["turn"]))
check(state["retries"] == 0, "%s: no answer was refused (MSG_RETRY x%d)" % (label, state["retries"]))
fields = [(turn, prev, cur) for turn, code, prev, cur in state["moves"] if code == PROBE_FIELD]
to_field = [(turn, cur[2]) for turn, prev, cur in fields if cur[0] == 0 and cur[1] == LOCATION_SZONE]
left = [(turn, prev[2], cur[1]) for turn, prev, cur in fields if prev[0] == 0 and prev[1] == LOCATION_SZONE]
hints = field_hints(seated[0].log)
if first_turn_fields == 1:
check(to_field == [(1, 5), (3, 6), (5, 5)],
"%s: seat 0's Field lands in sequence 5 on turn 1, seat 1's in sequence 6 on turn 3, seat 0's next in sequence 5 on turn 5 (%r)" % (label, to_field))
check(left == [(5, 5, LOCATION_GRAVE)],
"%s: only the sequence-5 Field left, to the Graveyard on turn 5; the sequence-6 Field never moved (%r)" % (label, left))
check(hints == [0x53D1, 0x61F2, 0x51F2],
"%s: the core saw it so: turn 1 seq 5, 1 field, slot 1 free; turn 3 seq 6, 2 fields, GetFieldCard(FZONE, 0) = the playing partner's, 1 = the other; turn 5 seq 5, 2 fields (%s)" % (label, ["0x%X" % h for h in hints]))
else:
check(to_field == [(1, 5), (1, 6), (3, 6), (5, 5)],
"%s: seat 0's first Field lands in sequence 5 and its second in the free sequence 6 on turn 1; seat 1's replaces sequence 6 on turn 3, seat 0's replaces sequence 5 on turn 5 (%r)" % (label, to_field))
check(left == [(3, 6, LOCATION_GRAVE), (5, 5, LOCATION_GRAVE)],
"%s: no Field left on turn 1; the sequence-6 Field went to the Graveyard on turn 3, the sequence-5 one on turn 5 (%r)" % (label, left))
check(hints == [0x53D1, 0x60F2, 0x61F2, 0x51F2],
"%s: the core saw it so: turn 1 seq 5 then seq 6 with 2 fields and GetFieldCard(FZONE, 0) = the first; turn 3 seq 6; turn 5 seq 5 (%s)" % (label, ["0x%X" % h for h in hints]))
check(all(not c.closed for c in seated), "%s: every seat is still connected" % label)
marks = marks_of(seated)
for c in seated[:2]:
c.send(CTOS_SURRENDER)
ok = pump(seated, lambda: all(match_overs(since(c, marks)) for c in seated), limit=10)
check(ok, "%s: side 0 surrendered: MATCH_OVER reached everyone" % label)
for c in seated:
c.close()
stop_dll(dll, thread, label)
finally:
os.chdir(here)
shutil.rmtree(root, ignore_errors=True)
def tag_two_fields_single(dll_path, port, label):
print("== tag two Field slots, %s (a Single room keeps a client without 0x1000)" % label)
root = make_workspace()
here = os.getcwd()
os.chdir(root)
try:
write_special(root, [])
dll, thread = host_dll(dll_path, port, 0)
h = Client("127.0.0.1", port, "tf-host")
h.log = list(h.join())
cap = server_capability(h.log)
check(cap == (12, 0xF7FF), "%s: the single server's capability is protocol 12, flags 0xF7FF (got %s)" % (label, cap))
h.send(CTOS_CAPABILITY, capability_bytes(9, 0x27FF))
h.log += h.drain(quiet=0.4)
check(h.seat == 0 and not error_msgs(h.log) and not h.closed and stamped(h.log, STOC_CAPABILITY, 0) == [capability_bytes(9, 0x27FF)],
"%s: a seat whose capability lacks 0x1000 stays and its CAPABILITY is relayed (errors %r, closed %r)" % (label, error_msgs(h.log), h.closed))
h.close()
stop_dll(dll, thread, label)
finally:
os.chdir(here)
shutil.rmtree(root, ignore_errors=True)
def tag_two_fields_suite(dll_path, port):
print()
print("hosting the tag two Field slots rooms from %s" % dll_path)
tag_two_fields_room(dll_path, port, "tag")
tag_two_fields_room(dll_path, port + 2, "tag, two in one turn", first_turn_fields=2)
tag_two_fields_single(dll_path, port + 1, "single")
# --- proposal 53 (TICKET-433): Tag shared Extra Deck --------------------------------------------
# With the setup pair ygol.tag.extra=shared the server sets option 0x200 and start_duel moves the
# waiting partner's Extra Deck into the live list; tag_swap leaves it there. Each card keeps the
# partner who brought it, sent as QUERY_TAG_MEMBER on Extra Deck refreshes of that duel only.
# Capability 0x4000, protocol 11. Without the pair the lists stay apart.
FEATURE_TAG_SHARED_EXTRA = 0x4000
QUERY_TAG_MEMBER = 0x1000000
DUEL_TAG_SHARED_EXTRA = 0x200
TAG_EXTRA_PAIR = "ygol.tag.extra=shared"
PROBE_EXTRA_SPELL = PROBE_CARD + 900
PROBE_SEAT_FUSIONS = [PROBE_CARD + 901 + seat for seat in range(4)]
SEAT_EXTRA = {0: [PROBE_SEAT_FUSIONS[0]] * 2, 1: [PROBE_SEAT_FUSIONS[1]], 2: [PROBE_SEAT_FUSIONS[2]], 3: [PROBE_SEAT_FUSIONS[3]] * 3}
MSG_UPDATE_DATA, MSG_UPDATE_CARD, LOCATION_EXTRA = 6, 7, 0x40
EXTRA_SPELL_LUA = """--Probe Extra Spell (proposal 53): return your face-up Fusion Monster to the Extra Deck; with none, Special Summon 1 from it.
local s,id,o=GetID()
function s.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(s.target)
e1:SetOperation(s.activate)
c:RegisterEffect(e1)
end
function s.onfield(c)
return c:IsFaceup() and c:IsType(TYPE_FUSION)
end
function s.inextra(c)
return c:IsType(TYPE_FUSION)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(s.onfield,tp,LOCATION_MZONE,0,1,nil) or Duel.IsExistingMatchingCard(s.inextra,tp,LOCATION_EXTRA,0,1,nil) end
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local f=Duel.GetFirstMatchingCard(s.onfield,tp,LOCATION_MZONE,0,nil)
if f then
Duel.SendtoDeck(f,nil,0,REASON_EFFECT)
return
end
local tc=Duel.SelectMatchingCard(tp,s.inextra,tp,LOCATION_EXTRA,0,1,1,nil):GetFirst()
if tc then Duel.SpecialSummon(tc,0,tp,tp,true,false,POS_FACEUP) end
end
"""
def query_records(d, at):
# (flag, code or None, value of QUERY_TAG_MEMBER or None) per record of a query buffer
out = []
while at + 4 <= len(d):
(clen,) = struct.unpack_from("<i", d, at)
if clen < 4:
break
if clen >= 8:
(flag,) = struct.unpack_from("<I", d, at + 4)
code = struct.unpack_from("<I", d, at + 8)[0] if flag & 1 and clen >= 12 else None
member = struct.unpack_from("<I", d, at + clen - 4)[0] if flag & QUERY_TAG_MEMBER else None
out.append((flag, code, member))
at += clen
return out
def extra_refreshes(pkts, side):
return [query_records(d, 3) for p, d in pkts if p == 0x01 and len(d) >= 3 and d[0] == MSG_UPDATE_DATA and d[1] == side and d[2] == LOCATION_EXTRA]
def other_queries_with_bit(pkts):
bad = 0
for p, d in pkts:
if p != 0x01 or len(d) < 3:
continue
if d[0] == MSG_UPDATE_DATA and d[2] != LOCATION_EXTRA:
bad += sum(1 for r in query_records(d, 3) if r[0] & QUERY_TAG_MEMBER)
elif d[0] == MSG_UPDATE_CARD:
bad += sum(1 for r in query_records(d, 4) if r[0] & QUERY_TAG_MEMBER)
return bad
def start_extra_counts(pkts):
# MSG_START: player, rule, i32 lp[2], u16 deck0, extra0, deck1, extra1
return [(struct.unpack_from("<H", d, 13)[0], struct.unpack_from("<H", d, 17)[0]) for p, d in pkts if p == 0x01 and len(d) >= 19 and d[0] == MSG_START]
def members_by_code(records):
return sorted((r[1], r[2]) for r in records)
def replay_duel_parts(body, flag):
# the replay body up to the responses: (opt, start_lp, start_hand, draw_count, decks, responses)
at = 4 + struct.unpack_from("<I", body, 0)[0] if flag & REPLAY_YGOL_SETUP_PAIRS else 0
at += 4 * 40
start_lp, start_hand, draw_count, opt = struct.unpack_from("<iiiI", body, at)
at += 16
decks = []
for _ in range(8):
(n,) = struct.unpack_from("<i", body, at)
decks.append(list(struct.unpack_from("<%dI" % n, body, at + 4)))
at += 4 + 4 * n
responses = []
while at < len(body):
n = body[at]
responses.append(body[at + 1:at + 1 + n])
at += 1 + n
return opt, start_lp, start_hand, draw_count, decks, responses
def play_replay_back(dll, seeds, parts, pairs):
# the library plays the recorded duel again, as a replay reader does: what start_duel made, then the Summons
opt, start_lp, start_hand, draw_count, decks, responses = parts
h = ctypes.c_ssize_t
dll.create_duel_v2.restype = h
dll.create_duel_v2.argtypes = [ctypes.POINTER(ctypes.c_uint32)]
dll.set_player_info.argtypes = [h, ctypes.c_int32, ctypes.c_int32, ctypes.c_int32, ctypes.c_int32]
dll.set_registry_value.argtypes = [h, ctypes.c_char_p, ctypes.c_char_p]
dll.preload_script.argtypes = [h, ctypes.c_char_p]
dll.new_card.argtypes = [h, ctypes.c_uint32, ctypes.c_uint8, ctypes.c_uint8, ctypes.c_uint8, ctypes.c_uint8, ctypes.c_uint8]
dll.new_tag_card.argtypes = [h, ctypes.c_uint32, ctypes.c_uint8, ctypes.c_uint8]
dll.start_duel.argtypes = [h, ctypes.c_uint32]
dll.process.restype = ctypes.c_uint32
dll.process.argtypes = [h]
dll.get_message.argtypes = [h, ctypes.c_char_p]
dll.set_responseb.argtypes = [h, ctypes.c_char_p]
dll.query_field_count.argtypes = [h, ctypes.c_uint8, ctypes.c_uint8]
dll.query_field_card.argtypes = [h, ctypes.c_uint8, ctypes.c_uint8, ctypes.c_uint32, ctypes.c_char_p, ctypes.c_int32]
dll.ygol_query_tag_cards.argtypes = [h, ctypes.c_uint8, ctypes.c_char_p]
dll.end_duel.argtypes = [h]
d = dll.create_duel_v2((ctypes.c_uint32 * 8)(*seeds))
for pair in pairs:
k, v = pair.split("=", 1)
dll.set_registry_value(d, k.encode(), v.encode())
dll.set_player_info(d, 0, start_lp, start_hand, draw_count)
dll.set_player_info(d, 1, start_lp, start_hand, draw_count)
dll.preload_script(d, b"./script/init.lua")
for i, codes in enumerate(decks):
team, kind = i // 4, i % 4
for code in codes:
location = LOCATION_EXTRA if kind % 2 else 0x01
if kind < 2:
dll.new_card(d, code, team, team, location, 0, 0x08)
else:
dll.new_tag_card(d, code, team, location)
dll.start_duel(d, opt)
buf = ctypes.create_string_buffer(0x40000)
out = {"counts": (dll.query_field_count(d, 0, LOCATION_EXTRA), dll.query_field_count(d, 1, LOCATION_EXTRA))}
def extra(team):
n = dll.query_field_card(d, team, LOCATION_EXTRA, 0x1 | QUERY_TAG_MEMBER, buf, 0)
return members_by_code(query_records(buf.raw[:n], 0))
def waiting_extra(team):
dll.ygol_query_tag_cards(d, team, buf)
return buf.raw[2]
out["opening"] = (extra(0), extra(1))
out["waiting"] = (waiting_extra(0), waiting_extra(1))
stream = b""
left = list(responses)
for _ in range(100000):
r = dll.process(d)
n = r & 0x0FFFFFFF
if n:
got = dll.get_message(d, buf)
stream += buf.raw[:got]
if r & 0x20000000:
break
if r & 0x10000000:
if not left:
break
one = ctypes.create_string_buffer(left.pop(0), 256)
dll.set_responseb(d, one)
out["responses_left"] = len(left)
out["summons"] = []
at = 0
while True:
at = stream.find(bytes([MSG_SPSUMMONING]), at)
if at < 0 or at + 5 > len(stream):
break
(code,) = struct.unpack_from("<I", stream, at + 1)
if code in PROBE_SEAT_FUSIONS:
out["summons"].append(code)
at += 1
out["end_extra"] = extra(0)
dll.end_duel(d)
return out
def tag_shared_extra_room(dll_path, port, label, shared):
print("== tag shared Extra Deck, %s" % label)
F0, F1, F2, F3 = PROBE_SEAT_FUSIONS
root = make_workspace()
here = os.getcwd()
os.chdir(root)
try:
pairs = [TAG_EXTRA_PAIR] if shared else []
write_special(root, pairs)
dll, thread = host_dll(dll_path, port, 2, " ".join(pairs))
seated = []
for i in range(4):
c = Client("127.0.0.1", port, "se-seat%d" % i)
c.log = list(c.join())
seated.append(c)
check([c.seat for c in seated] == [0, 1, 2, 3], "%s: four seats (%r)" % (label, [c.seat for c in seated]))
cap = server_capability(seated[0].log)
check(cap == (12, 0xF7FF), "%s: the tag server's capability is protocol 12, flags 0xF7FF (got %s)" % (label, cap))
drain_all(seated)
old = Client("127.0.0.1", port, "se-old")
old.log = list(old.join())
old.send(CTOS_CAPABILITY, capability_bytes(10, 0x37FF))
old.log += old.drain(quiet=0.4)
check(old.seat == OBSERVER and error_msgs(old.log) == [ERRMSG_VERERROR] and old.closed,
"%s: a joiner with 0x1000 but without 0x4000 gets ERROR_MSG VERERROR and is disconnected (seat %r, errors %r, closed %r)" % (label, old.seat, error_msgs(old.log), old.closed))
drain_all(seated)
watcher = Client("127.0.0.1", port, "se-watch")
watcher.log = list(watcher.join())
drain_all(seated + [watcher])
for c in seated:
spell = PROBE_EXTRA_SPELL if c.seat < 2 else PROBE_KNIGHT
c.send(CTOS_UPDATE_DECK, deck_bytes([spell] * 40 + SEAT_EXTRA[c.seat]))
pump(seated, lambda: False, limit=0.8)
seated[0].send(CTOS_HS_START)
state = {"turn": 0, "acted": 0, "retries": 0, "selects": [], "summons": [], "swaps": []}
picks = {1: F1, 5: F0} if shared else {1: F0}
def answer(c, payload):
c.send(CTOS_TIME_CONFIRM)
c.send(CTOS_RESPONSE, payload)
def play(until, limit):
deadline = time.time() + limit
while time.time() < deadline:
watcher.log += watcher.drain(quiet=0.02, limit=0.1)
for c in seated:
for pid, d in c.drain(quiet=0.02, limit=0.2):
c.log.append((pid, d))
if pid == STOC_SELECT_TP:
c.send(CTOS_TP_RESULT, bytes([1 if c.seat == 0 else 0])) # side A (seats 0 + 1) goes first
continue
if pid != 0x01 or not d:
continue
t = d[0]
if t == MSG_NEW_TURN and c.seat == 0:
state["turn"] += 1
elif t == MSG_TAG_SWAP and c.seat == 0 and d[1] == 0:
state["swaps"].append((state["turn"], d[3], d[4], len(c.log) - 1))
elif t == MSG_SPSUMMONING and c.seat == 0:
state["summons"].append((state["turn"], struct.unpack_from("<I", d, 1)[0]))
elif t == MSG_RETRY:
state["retries"] += 1
elif t == MSG_SELECT_IDLECMD:
n = 2
for k in range(5):
n += 1 + d[n] * 7
activatable = d[n]
if activatable and state["acted"] != state["turn"]:
state["acted"] = state["turn"]
answer(c, struct.pack("<i", 5)) # activate the first card: the Spell
else:
answer(c, struct.pack("<i", 7)) # to the End Phase
elif t == MSG_SELECT_CARD:
cards = [struct.unpack_from("<II", d, 6 + 8 * i) for i in range(d[5])]
state["selects"].append((state["turn"], sorted((info_location(v)[2], code) for code, v in cards)))
want = picks.get(state["turn"])
answer(c, bytes([1, next((i for i, card in enumerate(cards) if card[0] == want), 0)]))
elif t == MSG_SELECT_TRIBUTE:
answer(c, bytes([1, 0]))
elif t == MSG_SELECT_CHAIN:
answer(c, struct.pack("<i", -1))
elif t in (MSG_SELECT_PLACE, MSG_SELECT_DISFIELD):
answer(c, first_free_zone(d))
elif t == MSG_SELECT_POSITION:
answer(c, struct.pack("<i", next(b for b in (1, 2, 4, 8) if d[6] & b)))
elif t in (MSG_SELECT_EFFECTYN, MSG_SELECT_YESNO):
answer(c, struct.pack("<i", 1))
elif t in (MSG_SELECT_OPTION, MSG_SELECT_BATTLECMD):
answer(c, struct.pack("<i", 0 if t == MSG_SELECT_OPTION else 3))
if until():
return True
if any(c.closed for c in seated):
return False
return until()
last_turn = 6 if shared else 4
ok = play(lambda: state["turn"] >= last_turn, limit=60)
check(ok, "%s: the duel reached turn %d (turn %d)" % (label, last_turn, state["turn"]))
check(state["retries"] == 0, "%s: no answer was refused (MSG_RETRY x%d)" % (label, state["retries"]))
for c in seated:
check(start_extra_counts(c.log) == [(3, 4) if shared else (2, 1)], "%s: seat %d's MSG_START gives the Extra Deck counts %s (%r)" % (label, c.seat, (3, 4) if shared else (2, 1), start_extra_counts(c.log)))
check(other_queries_with_bit(c.log) == 0, "%s: seat %d: no other query carries QUERY_TAG_MEMBER (%d)" % (label, c.seat, other_queries_with_bit(c.log)))
if shared:
opening = {0: [(F0, 0), (F0, 0), (F1, 1)], 1: [(F2, 0), (F3, 1), (F3, 1), (F3, 1)]}
for c in seated:
own, other = c.seat // 2, 1 - c.seat // 2
first = extra_refreshes(c.log, own)
check(bool(first) and members_by_code(first[0]) == opening[own], "%s: seat %d's first Extra Deck refresh lists both partners' cards with the partner each came from (%r)" % (label, c.seat, members_by_code(first[0]) if first else None))
masked = extra_refreshes(c.log, other)
check(bool(masked) and len(masked[0]) == len(opening[other]) and all(r[0] == 0 for r in masked[0]), "%s: seat %d's copy of the other team's refresh is masked, flag 0, no value (%r)" % (label, c.seat, masked[0] if masked else None))
cards = partner_cards(c.log, own)
check(bool(cards) and all(g[3] == [] for g in cards) and len(cards[0][2]) == 5, "%s: seat %d's TAG_PARTNER_CARDS report an Extra count of 0, and the waiting hand stays (%r)" % (label, c.seat, [(g[3], len(g[2] or [])) for g in cards]))
for team in (0, 1):
first = extra_refreshes(watcher.log, team)
check(bool(first) and members_by_code(first[0]) == opening[team], "%s: the watcher's first refresh of side %d has the values too (%r)" % (label, team, members_by_code(first[0]) if first else None))
check(state["selects"][:1] == [(1, [(0, F0), (1, F0), (2, F1)])],
"%s: on turn 1 seat 0 is offered both partners' Fusions, in sequences 0, 1, 2 (%r)" % (label, state["selects"][:1]))
check(state["summons"] == [(1, F1), (5, F0)], "%s: seat 0 Summons seat 1's monster on turn 1, its own on turn 5 (%r)" % (label, state["summons"]))
check([s[:3] for s in state["swaps"]] == [(3, 2, 0), (5, 3, 0)],
"%s: MSG_TAG_SWAP keeps the one list: 2 cards on turn 3, 3 on turn 5 when seat 1 returned the Fusion (%r)" % (label, [s[:3] for s in state["swaps"]]))
log = seated[0].log
after = extra_refreshes(log[state["swaps"][1][3]:], 0) if len(state["swaps"]) > 1 else []
check(bool(after) and members_by_code(after[0]) == [(F0, 0), (F0, 0), (F1, 1)], "%s: after the swap of turn 5 the Fusion that moved still says partner 1 (%r)" % (label, members_by_code(after[0]) if after else None))
late = Client("127.0.0.1", port, "se-late")
late.log = list(late.join())
late.log += late.drain(quiet=0.6)
snapshot = extra_refreshes(late.log, 0)
check(bool(snapshot) and members_by_code(snapshot[0]) == [(F0, 0), (F1, 1)], "%s: a late watcher's snapshot refresh has the values (flag 0xefffff + the bit) (%r)" % (label, members_by_code(snapshot[0]) if snapshot else None))
late.close()
else:
for c in seated + [watcher]:
for team in (0, 1):
records = [r for refresh in extra_refreshes(c.log, team) for r in refresh]
check(bool(records) and not any(r[0] & QUERY_TAG_MEMBER for r in records), "%s: %s: no Extra Deck refresh of side %d carries the bit" % (label, c.name, team))
cards = partner_cards(seated[0].log, 0)
check(bool(cards) and cards[0][3] == [F1], "%s: the opening TAG_PARTNER_CARDS report the waiting partner's Extra Deck (%r)" % (label, cards[0][3] if cards else None))
check(state["selects"][:1] == [(1, [(0, F0), (1, F0)])], "%s: on turn 1 seat 0 is offered only its own Fusions (%r)" % (label, state["selects"][:1]))
check(state["summons"] == [(1, F0)], "%s: seat 0 Summons its own monster on turn 1 (%r)" % (label, state["summons"]))
check([s[:3] for s in state["swaps"]] == [(3, 1, 0)], "%s: the swap of turn 3 brings seat 1's Extra Deck (%r)" % (label, [s[:3] for s in state["swaps"]]))
marks = marks_of(seated)
for c in seated[:2]:
c.send(CTOS_SURRENDER)
ok = pump(seated, lambda: all(match_overs(since(c, marks)) for c in seated), limit=10)
check(ok, "%s: side 0 surrendered: MATCH_OVER reached everyone" % label)
reps = replays(seated[0])
if check(len(reps) == 1, "%s: one REPLAY arrived (%d)" % (label, len(reps))):
flag, seeds, body = reps[0]
parts = replay_duel_parts(body, flag)
check(bool(parts[0] & DUEL_TAG_SHARED_EXTRA) == shared, "%s: the replay's opt %s option 0x200 (opt 0x%x)" % (label, "has" if shared else "does not have", parts[0]))
back = play_replay_back(dll, seeds, parts, pairs)
if shared:
check(back["counts"] == (3, 4) and back["waiting"] == (0, 0), "%s: replay: start_duel merged: live Extra Decks 3 and 4, waiting lists 0 (%r, %r)" % (label, back["counts"], back["waiting"]))
check(back["opening"] == ([(F0, 0), (F0, 0), (F1, 1)], [(F2, 0), (F3, 1), (F3, 1), (F3, 1)]), "%s: replay: the query gives each card its partner (%r)" % (label, back["opening"]))
check(back["summons"] == [F1, F0], "%s: replay: the recorded answers Summon the waiting partner's monster, then seat 0's (%r)" % (label, back["summons"]))
check(back["responses_left"] == 0 and back["end_extra"] == [(F0, 0), (F1, 1)], "%s: replay: every answer was used and the Extra Deck ends as it did live (%d left, %r)" % (label, back["responses_left"], back["end_extra"]))
else:
check(back["counts"] == (2, 1) and back["waiting"] == (1, 3), "%s: replay: the lists stay apart: live 2 and 1, waiting 1 and 3 (%r, %r)" % (label, back["counts"], back["waiting"]))
check(back["summons"] == [F0] and back["responses_left"] == 0, "%s: replay: the recorded answers Summon the same monster (%r, %d left)" % (label, back["summons"], back["responses_left"]))
for c in seated + [watcher]:
c.close()
stop_dll(dll, thread, label)
finally:
os.chdir(here)
shutil.rmtree(root, ignore_errors=True)
def tag_shared_extra_single(dll_path, port, label):
print("== tag shared Extra Deck, %s (a Single room keeps a client without 0x4000)" % label)
root = make_workspace()
here = os.getcwd()
os.chdir(root)
try:
write_special(root, [])
dll, thread = host_dll(dll_path, port, 0)
h = Client("127.0.0.1", port, "se-host")
h.log = list(h.join())
h.send(CTOS_CAPABILITY, capability_bytes(10, 0x37FF))
h.log += h.drain(quiet=0.4)
check(h.seat == 0 and not error_msgs(h.log) and not h.closed, "%s: a seat whose capability lacks 0x4000 stays (errors %r, closed %r)" % (label, error_msgs(h.log), h.closed))
h.close()
stop_dll(dll, thread, label)
finally:
os.chdir(here)
shutil.rmtree(root, ignore_errors=True)
def tag_shared_extra_suite(dll_path, port):
print()
print("hosting the tag shared Extra Deck rooms from %s" % dll_path)
tag_shared_extra_room(dll_path, port, "pair present", True)
tag_shared_extra_room(dll_path, port + 1, "pair absent", False)
tag_shared_extra_single(dll_path, port + 2, "single")
# --- v1.7.0 (proposal 55 / TICKET-451): prompt context ----------------------------
STOC_PROMPT_CONTEXT = 0x44
NAMES.update({0x44: "PROMPT_CONTEXT"})
PROBE_ASK = PROBE_CARD + 1000
PROBE_ASK_FUSION = PROBE_CARD + 1001
LOCATION_DECK = 0x01
MSG_ANNOUNCE_NUMBER = 143
PROMPT_MSGS = {10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 22, 23, 24, 25, 26, 140, 141, 142, 143}
ASK_LUA = """--Probe Ask (TICKET-451): two effects that never run, then an Activate that asks in its cost, target and operation,
--runs Probe Ask Fusion's material procedure (which asks too) and asks again, shuffles itself into the deck and asks
--the opponent, then its controller.
local s,id,o=GetID()
function s.initial_effect(c)
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_SINGLE)
e0:SetCode(EFFECT_UPDATE_ATTACK)
e0:SetRange(LOCATION_MZONE)
e0:SetValue(0)
c:RegisterEffect(e0)
local e1=e0:Clone()
e1:SetCode(EFFECT_UPDATE_DEFENSE)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(id*16+1)
e2:SetCategory(CATEGORY_DICE)
e2:SetType(EFFECT_TYPE_ACTIVATE)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetCost(s.cost)
e2:SetTarget(s.target)
e2:SetOperation(s.activate)
c:RegisterEffect(e2)
end
function s.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SelectYesNo(tp,id*16+2)
end
function s.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SelectOption(tp,id*16+3,id*16+4)
end
function s.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
Duel.SelectYesNo(tp,id*16+5)
local fc=Duel.GetFirstMatchingCard(Card.IsCode,tp,LOCATION_EXTRA,0,nil,id+1)
if fc then Duel.SelectFusionMaterial(tp,fc,Duel.GetFieldGroup(tp,LOCATION_HAND,0)) end
Duel.SelectYesNo(tp,id*16+8)
Duel.AnnounceLevel(tp,1,12)
Duel.AnnounceNumber(tp,1,2,3,4,5,6)
c:CancelToGrave()
Duel.SendtoDeck(c,nil,0,REASON_EFFECT)
Duel.SelectYesNo(1-tp,id*16+6)
Duel.SelectYesNo(tp,id*16+7)
end
"""
ASK_DESCRIPTION = PROBE_ASK * 16 + 1
ASK_INDEX = 2
ASK_FUSION_LUA = """--Probe Ask Fusion (TICKET-451): a Fusion Monster whose material procedure (its second effect) asks a yes/no, and
--whose third effect is an optional trigger from the Extra Deck in its controller's End Phase (the core asks "use it?").
local s,id,o=GetID()
function s.initial_effect(c)
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_SINGLE)
e0:SetCode(EFFECT_UPDATE_ATTACK)
e0:SetRange(LOCATION_MZONE)
e0:SetValue(0)
c:RegisterEffect(e0)
local e1=Effect.CreateEffect(c)
e1:SetDescription(id*16+1)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCondition(s.fcon)
e1:SetOperation(s.fop)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(id*16+3)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetRange(LOCATION_EXTRA)
e2:SetCountLimit(1)
e2:SetCondition(s.econ)
e2:SetOperation(s.eop)
c:RegisterEffect(e2)
end
function s.econ(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function s.eop(e,tp,eg,ep,ev,re,r,rp)
end
function s.fcon(e,g,gc,chkf)
return true
end
function s.fop(e,tp,eg,ep,ev,re,r,rp,gc,chkf)
Duel.SelectYesNo(tp,id*16+2)
Duel.AnnounceNumber(tp,7,8)
Duel.SetFusionMaterial(Group.CreateGroup())
end
"""
ASK_FUSION_INDEX = 1
ASK_TRIGGER_INDEX = 2
def prompt_context(d):
# 23-byte record + the prompt's MSG id: version, has effect, u32 code, controller, location, sequence, position,
# u64 description, u16 effect index, phase, chain link, announce kind, prompt
keys = ("version", "has", "code", "controller", "location", "sequence", "position", "description", "index", "phase", "chain", "announce", "prompt")
return dict(zip(keys, struct.unpack("<BBIBBBBQHBBBB", d)))
def prompts_with_context(c):
# every prompt this seat got, with the PROMPT_CONTEXT packet right before it (None when there was none)
out = []
for i, (p, d) in enumerate(c.log):
if p == 0x01 and d and d[0] in PROMPT_MSGS:
prev = c.log[i - 1] if i else (None, b"")
ctx = prompt_context(prev[1]) if prev[0] == STOC_PROMPT_CONTEXT and len(prev[1]) == 24 else None
out.append((d[0], d, ctx))
return out
def contexts_of(c):
return [d for p, d in c.log if p == STOC_PROMPT_CONTEXT]
def is_none_context(ctx, prompt):
return ctx == {"version": 1, "has": 0, "code": 0, "controller": 0, "location": 0, "sequence": 0, "position": 0,
"description": 0, "index": 0xFFFF, "phase": 0, "chain": 0, "announce": 0, "prompt": prompt}
def prompt_context_room(dll_path, port, label, mode, opponent_bit=True, fusion_first=False):
seats = 4 if mode == 2 else 2
print("== prompt context, %s (%d seats + a watcher that advertises 0x8000; the first player activates Probe Ask)" % (label, seats))
root = make_workspace()
here = os.getcwd()
os.chdir(root)
seen = {}
try:
db = sqlite3.connect(os.path.join(root, "cards.cdb"))
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 2, 0, 0, 0, 0, 0, 0)", (PROBE_ASK,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Ask', ''" + ", ''" * 16 + ")", (PROBE_ASK,))
db.execute("INSERT INTO datas VALUES(?, 3, 0, 0, 65, 2000, 2000, 6, 1, 16, 0)", (PROBE_ASK_FUSION,))
db.execute("INSERT INTO texts VALUES(?, 'Probe Ask Fusion', ''" + ", ''" * 16 + ")", (PROBE_ASK_FUSION,))
db.commit()
db.close()
with open(os.path.join(root, "script", "c%d.lua" % PROBE_ASK), "w", newline="\n") as f:
f.write(ASK_LUA)
with open(os.path.join(root, "script", "c%d.lua" % PROBE_ASK_FUSION), "w", newline="\n") as f:
f.write(ASK_FUSION_LUA)
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("pc-seat%d" % i) for i in range(seats)]
w = client("pc-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]))
cap = server_capability(seated[0].log)
check(cap == (12, 0xF7FF), "%s: the server's capability is protocol 12, flags 0xF7FF (got %s)" % (label, cap))
bitless = set()
for c in everyone:
if c is seated[-1] and not opponent_bit:
c.send(CTOS_CAPABILITY, capability_bytes(12, 0x77FF))
bitless.add(c)
else:
c.send(CTOS_CAPABILITY, capability_bytes(12, 0xF7FF))
drain_all(everyone)
check(not any(c.closed for c in everyone), "%s: every joiner stays, with or without 0x8000" % label)
for c in seated:
c.send(CTOS_UPDATE_DECK, deck_bytes([PROBE_ASK_FUSION] + [PROBE_ASK] * 40 if fusion_first else [PROBE_ASK] * 40 + [PROBE_ASK_FUSION]))
pump(everyone, lambda: False, limit=0.8)
seated[0].send(CTOS_HS_START)
state = {"turn": 0, "activated": None, "bp": False, "done": False, "retries": 0}
def answer(c, payload):
c.send(CTOS_TIME_CONFIRM)
c.send(CTOS_RESPONSE, payload)
def play(limit):
deadline = time.time() + limit
while time.time() < deadline:
w.log += w.drain(quiet=0.02, limit=0.1)
for c in seated:
for pid, d in c.drain(quiet=0.02, limit=0.2):
c.log.append((pid, d))
if pid == STOC_SELECT_TP:
c.send(CTOS_TP_RESULT, bytes([1 if c.seat == 0 else 0])) # seat 0's side goes first
continue
if pid != 0x01 or not d:
continue
t = d[0]
if t == MSG_NEW_TURN and c is seated[0]:
state["turn"] += 1
elif t == MSG_RETRY:
state["retries"] += 1
elif t == MSG_SELECT_IDLECMD:
if state["turn"] == 1 and state["activated"] is None:
state["activated"] = c
answer(c, struct.pack("<i", 5)) # activate the first card: a Probe Ask
elif state["turn"] == 1:
answer(c, struct.pack("<i", 7)) # to the End Phase
elif mode != 2 and not state["bp"]:
state["bp"] = True
answer(c, struct.pack("<i", 6)) # to the Battle Phase
else:
state["done"] = True # Tag: turn 2 has no Battle Phase; stop on its idle prompt
elif t == MSG_SELECT_BATTLECMD:
state["done"] = True
elif t == MSG_SELECT_CHAIN:
answer(c, struct.pack("<i", -1))
elif t in (MSG_SELECT_PLACE, MSG_SELECT_DISFIELD):
answer(c, first_free_zone(d))
elif t in (MSG_SELECT_EFFECTYN, MSG_SELECT_YESNO):
answer(c, struct.pack("<i", 1))
elif t in (MSG_SELECT_OPTION, MSG_ANNOUNCE_NUMBER):
answer(c, struct.pack("<i", 0))
if state["done"]:
return True
if any(c.closed for c in seated):
return False
return state["done"]
ok = play(limit=30)
check(ok, "%s: the duel reached the second player's %s prompt (turn %d)" % (label, "idle" if mode == 2 else "battle", state["turn"]))
check(state["retries"] == 0, "%s: no answer was refused (MSG_RETRY x%d)" % (label, state["retries"]))
a = state["activated"]
if not check(a is not None, "%s: a seat activated Probe Ask on turn 1" % label):
return seen
for c in seated:
got = prompts_with_context(c)
if c in bitless:
check(not contexts_of(c), "%s: %s advertised no 0x8000 and got no PROMPT_CONTEXT (%d)" % (label, c.name, len(contexts_of(c))))
continue
missing = [hex(t) for t, _, ctx in got if ctx is None or ctx["prompt"] != t]
check(not missing, "%s: %s: each of its %d prompts came right after a 24-byte PROMPT_CONTEXT naming that prompt (missing: %s)" % (label, c.name, len(got), missing))
check(len(contexts_of(c)) == len(got), "%s: %s: one PROMPT_CONTEXT per prompt, none on its own (%d contexts, %d prompts)" % (label, c.name, len(contexts_of(c)), len(got)))
check(not contexts_of(w), "%s: the watcher advertised 0x8000 and got no PROMPT_CONTEXT (%d)" % (label, len(contexts_of(w))))
mine = [(t, d, ctx) for t, d, ctx in prompts_with_context(a) if ctx]
player = next((d[1] for t, d, ctx in mine if t == MSG_SELECT_IDLECMD), None)
idle = [ctx for t, d, ctx in mine if t == MSG_SELECT_IDLECMD]
check(bool(idle) and all(is_none_context(ctx, MSG_SELECT_IDLECMD) for ctx in idle),
"%s: the idle prompt's context says no effect: every field 0, index 0xFFFF (%s)" % (label, idle[:1]))
chains = [ctx for c in seated for t, d, ctx in prompts_with_context(c) if t == MSG_SELECT_CHAIN and ctx]
check(all(is_none_context(ctx, MSG_SELECT_CHAIN) for ctx in chains), "%s: every chain prompt's context says no effect (%d)" % (label, len(chains)))
asks = [ctx for t, d, ctx in mine if ctx["has"] and ctx["prompt"] in (MSG_SELECT_YESNO, MSG_SELECT_OPTION)]
shape = [(ctx["prompt"], ctx["phase"], ctx["code"], ctx["chain"]) for ctx in asks]
Y, O, A, F = MSG_SELECT_YESNO, MSG_SELECT_OPTION, PROBE_ASK, PROBE_ASK_FUSION
check(shape == [(Y, 1, A, 1), (O, 2, A, 1), (Y, 3, A, 1), (Y, 3, F, 0), (Y, 3, A, 1), (Y, 3, A, 1)],
"%s: the activator's effect prompts are Probe Ask's cost yes/no (phase 1), target option (2), operation yes/no (3), then Probe Ask Fusion's material procedure inside that operation (3, chain link 0), then Probe Ask again: the outer context is back (chain link 1), then once more from the deck (%s)" % (label, shape))
if len(asks) == 6:
on_field = asks[:3] + [asks[4]]
check(all(ctx["code"] == PROBE_ASK and ctx["controller"] == player and ctx["location"] == LOCATION_SZONE and ctx["position"] & 0x5
and ctx["description"] == ASK_DESCRIPTION and ctx["index"] == ASK_INDEX and ctx["chain"] == 1 for ctx in on_field),
"%s: cost, target and both operation prompts name Probe Ask, its controller %r, face-up in the Spell & Trap Zone, description id*16+1, effect index 2, chain link 1 (%s)" % (label, player, on_field))
nested = asks[3]
check(nested["controller"] == player and nested["location"] == LOCATION_EXTRA and nested["index"] == ASK_FUSION_INDEX and nested["description"] == PROBE_ASK_FUSION * 16 + 1,
"%s: the nested procedure names Probe Ask Fusion in its controller's Extra Deck, effect index 1, its own description (%s)" % (label, nested))
last = asks[5]
check(last["location"] == LOCATION_DECK and last["index"] == ASK_INDEX and last["description"] == ASK_DESCRIPTION,
"%s: after it shuffled itself into the deck its controller still sees it: code, index 2, description, location Deck (%s)" % (label, last))
seen["index"] = [ctx["index"] for ctx in asks]
optional = [ctx for t, d, ctx in mine if t == MSG_SELECT_EFFECTYN]
check(len(optional) == 1 and optional[0]["has"] == 1 and optional[0]["code"] == PROBE_ASK_FUSION and optional[0]["controller"] == player
and optional[0]["location"] == LOCATION_EXTRA and optional[0]["index"] == ASK_TRIGGER_INDEX and optional[0]["description"] == PROBE_ASK_FUSION * 16 + 3
and optional[0]["phase"] == 4 and optional[0]["chain"] == 0,
"%s: the End Phase \"use this effect?\" for the optional trigger names Probe Ask Fusion in the Extra Deck, effect index 2, its description, phase 4 (ask), chain link 0 (%s)" % (label, optional))
if optional:
seen["index"] = seen.get("index", []) + [optional[0]["index"]]
announces = [(ctx["code"], ctx["phase"], ctx["announce"]) for t, d, ctx in mine if t == MSG_ANNOUNCE_NUMBER]
check(announces == [(PROBE_ASK_FUSION, 3, 0), (PROBE_ASK, 3, 1), (PROBE_ASK, 3, 2)],
"%s: announce kind: the Fusion's plain Duel.AnnounceNumber says 0, Probe Ask's Duel.AnnounceLevel 1 (level wins over dice), its dice effect's Duel.AnnounceNumber 2 (%s)" % (label, announces))
others = [ctx["announce"] for c in seated for t, d, ctx in prompts_with_context(c) if ctx and t != MSG_ANNOUNCE_NUMBER]
check(others and not any(others), "%s: every other prompt's context has announce kind 0 (%d prompts)" % (label, len(others)))
opponent = [c for c in seated if c is not a and any(t == MSG_SELECT_YESNO for t, _, _ in prompts_with_context(c))]
check(len(opponent) == 1, "%s: exactly one other seat answered the operation's yes/no (%s)" % (label, [c.name for c in opponent]))
if opponent and opponent[0] not in bitless:
hidden = [ctx for t, d, ctx in prompts_with_context(opponent[0]) if t == MSG_SELECT_YESNO and ctx]
check(len(hidden) == 1 and hidden[0]["has"] == 1 and hidden[0]["code"] == 0 and hidden[0]["index"] == 0xFFFF and hidden[0]["description"] == 0
and hidden[0]["location"] == LOCATION_DECK and hidden[0]["controller"] == player and hidden[0]["phase"] == 3 and hidden[0]["chain"] == 1 and hidden[0]["position"] & 0xA,
"%s: the opponent's yes/no names a hidden card: code 0, index 0xFFFF, description 0, but its controller, the Deck, face-down, phase 3, chain link 1 (%s)" % (label, hidden))
if mode == 2:
answering = {a} | set(opponent)
waiting = [c for c in seated if c not in answering]
check(len(waiting) == 2 and all(not contexts_of(c) for c in waiting),
"%s: the two waiting partners got no PROMPT_CONTEXT (%s)" % (label, [(c.name, len(contexts_of(c))) for c in waiting]))
else:
battle = [ctx for c in seated for t, d, ctx in prompts_with_context(c) if t == MSG_SELECT_BATTLECMD]
if opponent and opponent[0] not in bitless:
check(len(battle) == 1 and battle[0] is not None and is_none_context(battle[0], MSG_SELECT_BATTLECMD),
"%s: the battle prompt's context says no effect (%s)" % (label, battle))
marks = marks_of(seated)
for c in seated:
if (c.seat == 0) if mode != 2 else (c.seat in (0, 1)):
c.send(CTOS_SURRENDER)
ok = pump(seated, lambda: all(match_overs(since(c, marks)) for c in seated), limit=10)
check(ok, "%s: a surrender ended the match for everyone" % label)
for c in clients:
c.close()
stop_dll(dll, thread, label)
return seen
finally:
os.chdir(here)
shutil.rmtree(root, ignore_errors=True)
def prompt_context_suite(dll_path, port):
print()
print("hosting prompt context rooms from %s" % dll_path)
first = prompt_context_room(dll_path, port, "single", 0)
second = prompt_context_room(dll_path, port + 1, "single, second duel, other deck order, opponent without 0x8000", 0, opponent_bit=False, fusion_first=True)
prompt_context_room(dll_path, port + 2, "tag", 2)
expected = [ASK_INDEX] * 3 + [ASK_FUSION_INDEX] + [ASK_INDEX] * 2 + [ASK_TRIGGER_INDEX]
check(first.get("index") == second.get("index") == expected,
"the effect indexes are the same in two duels with a different deck order and seed: %s and %s" % (first.get("index"), second.get("index")))
if __name__ == "__main__":
sys.exit(main())