#!/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 # 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= 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("= 3: (ln,) = struct.unpack_from("= 2: return "(%d)" % struct.unpack_from("= 2 and struct.unpack_from(" 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(" 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(" 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("= 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("= 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("= 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("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("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(" 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("= 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("