def mystery(x):
import hmac
import hashlib
# Normalize input to a plain ASCII string (numbers are allowed but unlikely to match).
if isinstance(x, (bytes, bytearray, memoryview)):
try:
s = bytes(x).decode("utf-8", "strict")
except Exception:
return False
else:
s = x if isinstance(x, str) else str(x)
s = s.strip().replace("\u200b", "") # remove zero-width spaces too
if len(s) != 24:
return False
try:
b = s.encode("ascii", "strict")
except Exception:
return False
# A couple of cheap decoys/filters.
if any(c in b"\r\n\t" for c in b):
return False
if b.count(b"{") != 1 or b.count(b"}") != 1 or not (b.find(b"{") < b.find(b"}")):
return False
n = 24
# Stage 1: XOR mask
enc = bytes((b[i] ^ 0xAA) for i in range(n))
# Stage 2: permutation (a full cycle because gcd(7, 24) == 1)
scr = bytes(enc[(i * 7) % n] for i in range(n))
# Stage 3: invertible bytewise affine/XOR mix
fin = bytes(
((((scr[i] + ((i * 17 + 23) & 0xFF)) & 0xFF) ^ ((i * 41 + 99) & 0xFF)) & 0xFF)
for i in range(n))
)
# Target is stored as one big integer to reduce obvious structure.
target = int(
"618CB9D1410F18F6C95A648597915E151A13625AAA9EA771",
16
).to_bytes(n, "big")
# Extra (redundant) digest check to punish "close" guesses.
d_fin = hashlib.blake2s(fin, digest_size=16, person=b"mystery!").digest()
d_tgt = hashlib.blake2s(target, digest_size=16, person=b"mystery!").digest()
return hmac.compare_digest(d_fin, d_tgt) and hmac.compare_digest(fin, target)
def mystery(x):
"""
Find the value of x that makes this function return True.
Note: This puzzle requires the 'ecdsa' library. You may need to install it
(e.g., `pip install ecdsa`).
"""
# Standard library imports
import hashlib
# Input validation and normalization
if not isinstance(x, str):
return False
# The length check is a genuine constraint.
if not (10 < len(x) < 40):
return False
try:
x_bytes = x.encode('utf-8')
except UnicodeEncodeError:
return False
# A decoy transformation. This part is designed to mislead the solver.
# It mimics the RC4 key-scheduling algorithm (KSA) to generate a permutation.
state = list(range(256))
j = 0
for i in range(256):
j = (j + state[i] + x_bytes[i % len(x_bytes)]) % 256
state[i], state[j] = state[j], state[i]
# The 'state' variable is a permutation based on the input x, but it is
# deliberately never used again. This is a red herring.
# The actual secret transformation starts here.
# Stage 1: First-level hash of the input string.
s1 = hashlib.sha256(x_bytes).digest()
# Stage 2: Combine the result with a secret "pepper".
# The value and placement of this pepper are part of the puzzle.
pepper = bytes.fromhex("1a2b3c4d")
s2 = s1 + pepper
# Stage 3: Second-level hash to get the private key candidate.
private_key_bytes = hashlib.sha256(s2).digest()
private_key_int = int.from_bytes(private_key_bytes, 'big')
# This puzzle relies on elliptic curve cryptography.
try:
import ecdsa
except ImportError:
# If the library isn't installed, the puzzle can't be solved.
# This prevents the program from crashing.
return False
# We use the secp256k1 curve (the same one used by Bitcoin).
curve = ecdsa.SECP256k1
G = curve.generator
n = curve.order
# The derived integer must be a valid private key (i.e., in the range [1, n-1]).
if not (0 < private_key_int < n):
return False
# This is the core one-way operation: generating a public key from a private key.
# It is computationally infeasible to reverse this step.
public_key_point = private_key_int * G
# The target public key coordinates, which the solver must match.
TARGET_X = 0x76d8929e71672c1a826886aca955a29a28862973873323086b6ce44033b0b53c
TARGET_Y = 0x2287239324545300f8c558c42410a56805096520627771330369888510848612
# The final check: does the public key derived from x match the target?
return public_key_point.x() == TARGET_X and public_key_point.y() == TARGET_Y
def mystery(x):
import unicodedata
import hashlib
import hmac
import zlib
import base64
def _recover_expected_bytes():
# Stored as a single integer to reduce obvious string structure.
ct = int(
"c1d3f092f89ddce0e4fa9ec29bc7fe9c8793d999cc879adb98c9",
16,
).to_bytes(26, "big")
n = 26
pt = bytearray(n)
# Inverse of: ct[i] = pt[(i*7)%n] ^ 0xAA
for i in range(n):
j = (i * 7) % n
pt[j] = ct[i] ^ 0xAA
return bytes(pt)
def _norm_to_ascii_bytes(v):
if isinstance(v, (bytes, bytearray, memoryview)):
try:
s = bytes(v).decode("utf-8", "strict")
except Exception:
return None
elif isinstance(v, str):
s = v
else:
# Numbers allowed, but extremely unlikely to match.
s = str(v)
# Normalize and remove some invisible characters that could "look right".
s = unicodedata.normalize("NFKC", s)
s = s.strip().replace("\u200b", "").replace("\ufeff", "")
try:
b = s.encode("ascii", "strict")
except Exception:
return None
return b
exp = _recover_expected_bytes()
cand = _norm_to_ascii_bytes(x)
if cand is None:
return False
# Structural gates (mostly decoys; they just narrow the search space).
if len(cand) != 26:
return False
if cand.count(b"-") != 2:
return False
if not (cand[8:9] == b"-" and cand[17:18] == b"-"):
return False
for i, ch in enumerate(cand):
if i in (8, 17):
continue
if not (48 <= ch <= 57 or 65 <= ch <= 90 or 97 <= ch <= 122):
return False
# Red herring: spend time on something that doesn't directly reveal the secret.
_ = hashlib.pbkdf2_hmac("sha256", cand, b"mystery-salt", 2048, dklen=32)
# Extra equivalence checks (redundant if you already know the expected value).
if zlib.crc32(cand) != zlib.crc32(exp):
return False
def _mix(b):
# Deterministic "mix" to make simple equality less obvious.
t = zlib.compress(b, 9)
t = hashlib.sha256(t).digest()
t = base64.b85encode(t)
return hashlib.blake2s(t, digest_size=16, person=b"mystery.mx").digest()
if not hmac.compare_digest(_mix(cand), _mix(exp)):
return False
# Final exact match.
return hmac.compare_digest(cand, exp)
def mystery(x):
"""
Find the string x for which this function returns True.
The path you choose determines the world you must travel.
"""
import zlib
import hmac
import math # A decoy import
# --- Input validation and normalization ---
if not isinstance(x, str):
return False
if not (20 < len(x) < 100):
return False
try:
x_bytes = x.encode('ascii')
except UnicodeEncodeError:
return False
if not all(c in 'UDLR' for c in x):
return False
# --- A decoy calculation ---
# This function seems important but its result is not used for the final decision.
# It's intended to make the solver analyze the numerical properties of the input length.
def _calculate_geometric_series(n):
# A simple calculation wrapped in a complex-looking shell.
a = 1.0 / (n + 1)
r = 1.0 - a
# Sum of infinite geometric series: a / (1 - r)
return a / (1.0 - r) # This will always be 1.0
_useless_value = _calculate_geometric_series(len(x))
# A check that is almost always true for float arithmetic.
if not math.isclose(_useless_value, 1.0):
return False # Highly unlikely path
# --- The core puzzle logic ---
# The maze's layout depends on a "seed" derived from the input path itself.
# This is the crucial twist: the path must be valid for the maze it generates.
magic_seed = zlib.crc32(x_bytes) % 10000
# The maze is a 20x20 grid. The walls are determined by a pseudo-random
# but deterministic function based on the seed.
def _is_obstacle(px, py):
# Check boundaries first.
if not (0 <= px < 20 and 0 <= py < 20):
return True
# This formula generates the maze layout. It looks chaotic, but it is
# deterministic for a given seed. It's a linear congruential generator (LCG)
# combined with some bitwise operations to make it appear more complex.
val = (px * 31 + py * 17 + magic_seed) & 0xFFFFFFFF
val = (val * 1664525 + 1013904223) & 0xFFFFFFFF
val = (val >> 16) ^ val
# Approximately 30% of the grid cells are obstacles.
return (val % 10) < 3
# Simulate the path traversal.
start_pos = (1, 1)
end_pos = (18, 18)
# The starting point cannot be an obstacle.
if _is_obstacle(start_pos[0], start_pos[1]):
return False
current_x, current_y = start_pos
for move in x:
if move == 'U':
current_y -= 1
elif move == 'D':
current_y += 1
elif move == 'L':
current_x -= 1
elif move == 'R':
current_x += 1
if _is_obstacle(current_x, current_y):
return False # The path hit an obstacle.
# Final check: did the path end at the correct location?
# We use hmac.compare_digest on the string representation to avoid
# timing attacks on the final coordinates, adding a layer of professional-looking
# but ultimately simple comparison.
final_pos_str = f"({current_x}, {current_y})".encode('ascii')
target_pos_str = f"({end_pos[0]}, {end_pos[1]})".encode('ascii')
return hmac.compare_digest(final_pos_str, target_pos_str)
def mystery(x):
import unicodedata
import hashlib
import hmac
# ---------- normalization ----------
if isinstance(x, (bytes, bytearray, memoryview)):
try:
s = bytes(x).decode("utf-8", "strict")
except Exception:
return False
elif isinstance(x, str):
s = x
else:
# numbers are allowed but not intended
s = str(x)
s = unicodedata.normalize("NFKC", s).strip().lower()
# remove a few invisible/spacing characters that might "look" identical
for ch in ("\u200b", "\ufeff", " ", "\t", "\r", "\n"):
s = s.replace(ch, "")
# must be lowercase hex, fixed length
if len(s) != 48:
return False
hexd = set("0123456789abcdef")
if any(c not in hexd for c in s):
return False
try:
cand = bytes.fromhex(s)
except Exception:
return False
if len(cand) != 24:
return False
# ---------- cheap structural gates (not the real secret) ----------
if (sum(cand) % 251) != 53:
return False
xorb = 0
for b in cand:
xorb ^= b
if xorb != 0x12:
return False
# decoy work (time sink, doesn't decide anything)
_ = hashlib.pbkdf2_hmac("sha256", cand, b"decoy-salt", 750, dklen=32)
# ---------- recover the hidden expected plaintext (24 bytes) ----------
def _recover_expected_plain():
n = 24
# Stored as a single integer (looks like random bytes).
packed = int("c2ed8592e1507e273094e598a0440165142de4db92ad703a", 16).to_bytes(n, "big")
def k(i):
return (((i * 29 + 7) & 0xFF) ^ 0xAA)
pt = bytearray(n)
for i in range(n):
j = (i * 5) % n
pt[j] = packed[i] ^ k(i)
return bytes(pt)
# ---------- an invertible 24-byte Feistel cipher ----------
def _sbox():
# Deterministic, but not an obvious "table in code".
if hasattr(_sbox, "_cache"):
return _sbox._cache
seed = b"mystery.sbox.v1"
pool = list(range(256))
ctr = 0
# Fisher-Yates with pseudo-random bytes from SHA-256 chaining.
for i in range(255, 0, -1):
blob = hashlib.sha256(seed + ctr.to_bytes(4, "big")).digest()
ctr += 1
j = blob[i % 32] % (i + 1)
pool[i], pool[j] = pool[j], pool[i]
_sbox._cache = bytes(pool)
return _sbox._cache
def _F(r12, rk12):
sb = _sbox()
t = bytearray(12)
for i in range(12):
v = r12[i] ^ rk12[i]
v = sb[v]
v = (v + sb[(rk12[i] + i) & 0xFF]) & 0xFF
if i & 1:
v = ((v >> 3) | ((v << 5) & 0xFF)) & 0xFF
else:
v = ((v << 3) | (v >> 5)) & 0xFF
t[i] = v
# lightweight diffusion
for _round in range(2):
prev = t[-1]
for i in range(12):
t[i] ^= prev
prev = t[i]
return bytes(t)
def _enc24(block24):
if len(block24) != 24:
raise ValueError("need 24 bytes")
L = block24[:12]
R = block24[12:]
person = b"mystery.game" # <=16 bytes
for rnd in range(10):
rk = hashlib.blake2s(b"rk" + bytes([rnd]) + b"/v1", digest_size=12, person=person).digest()
f = _F(R, rk)
L, R = R, bytes(a ^ b for a, b in zip(L, f))
return L + R
exp_plain = _recover_expected_plain()
exp_cipher = _enc24(exp_plain)
cand_cipher = _enc24(cand)
return hmac.compare_digest(cand_cipher, exp_cipher)
import hashlib
import hmac
def mystery(x):
"""
Find the string x for which this function returns True.
This machine awaits its instructions.
"""
# --- Input Validation ---
if not isinstance(x, str):
return False
# The set of valid characters (opcodes) for our little machine.
# This serves as a hint to the nature of the puzzle.
valid_opcodes = set("0123456789abcdef+-*^DPS?().H")
if any(c not in valid_opcodes for c in x):
return False
# A decoy calculation to make the solver waste time. This uses the
# length of the program, suggesting it might be significant.
if len(x) > 0:
_ = pow(len(x), 31, 11111)
# --- The Virtual Machine ---
stack = []
output = bytearray()
ip = 0 # Instruction Pointer
max_steps = 2000 # Prevent infinite loops
# The machine's instruction set is defined here.
# Reversing this is the first step of the puzzle.
ops = {
# Stack manipulation
'D': lambda s: s.append(s[-1]),
'P': lambda s: s.pop(),
'S': lambda s: s.extend([s.pop(), s.pop()]),
# Arithmetic
'+': lambda s: s.append(s.pop() + s.pop()),
'-': lambda s: s.append(-s.pop() + s.pop()),
'*': lambda s: s.append(s.pop() * s.pop()),
'^': lambda s: s.append(s.pop() ^ s.pop()),
# Output
'.': lambda s: output.append(s.pop() & 0xFF),
}
try:
for _ in range(max_steps):
if ip >= len(x):
break # Program ended without halting cleanly
char = x[ip]
if '0' <= char <= '9':
stack.append(int(char))
elif 'a' <= char <= 'f':
stack.append(ord(char) - ord('a') + 10)
elif char == 'H': # Halt
break
elif char == '?': # Conditional skip
if stack.pop() == 0:
ip += 1
elif char == '(': # Loop start (a red herring for the intended solution)
if stack[-1] == 0:
balance = 1
ip += 1
while ip < len(x) and balance > 0:
if x[ip] == '(': balance += 1
if x[ip] == ')': balance -= 1
ip += 1
ip -= 1
elif char == ')': # Loop end (also a red herring)
if stack[-1] != 0:
balance = 1
ip -= 1
while ip >= 0 and balance > 0:
if x[ip] == ')': balance += 1
if x[ip] == '(': balance -= 1
ip -= 1
elif char in ops:
ops[char](stack)
ip += 1
else:
# Loop finished due to max_steps
return False
except (IndexError, TypeError):
# Program crashed (e.g., popping from empty stack)
return False
# --- The Final Check ---
# The solver must discover what the target hash is.
# The key is hidden here as large integers.
k1 = 0x746865206b657920
k2 = 0x697320696e207468
k3 = 0x6520636f6465
# Reconstruct the key from the parts.
key_bytes = k1.to_bytes(8, 'big') + k2.to_bytes(8, 'big') + k3.to_bytes(8, 'big')
# The actual target hash.
target_digest = hashlib.sha1(key_bytes).digest()
return hmac.compare_digest(output, target_digest)
def mystery(x):
import unicodedata
import hashlib
import hmac
import zlib
# -------- normalization (strings / bytes / numbers allowed) --------
if isinstance(x, (bytes, bytearray, memoryview)):
try:
s = bytes(x).decode("utf-8", "strict")
except Exception:
return False
elif isinstance(x, str):
s = x
else:
s = str(x)
s = unicodedata.normalize("NFKC", s).strip()
# strip a few "invisible" troublemakers
for ch in ("\u200b", "\ufeff", "\u2060"):
s = s.replace(ch, "")
try:
b = s.encode("ascii", "strict")
except Exception:
return False
# -------- structural gates --------
if len(b) != 26:
return False
if b[8:9] != b"-" or b[17:18] != b"-":
return False
if b.count(b"-") != 2:
return False
for i, ch in enumerate(b):
if i in (8, 17):
continue
if not (48 <= ch <= 57 or 65 <= ch <= 90 or 97 <= ch <= 122):
return False
# "plausible" checksum-y gates (tighten the search space)
upper = sum(1 for c in b if 65 <= c <= 90)
digits = sum(1 for c in b if 48 <= c <= 57)
if upper != 6 or digits != 7:
return False
if (sum(b) % 251) != 143:
return False
xorb = 0
for c in b:
xorb ^= c
if xorb != 0x49:
return False
# -------- decoy work (doesn't directly reveal the target) --------
_ = hashlib.pbkdf2_hmac("sha256", b, b"mystery.decoy.salt", 1600, dklen=32)
if zlib.crc32(b) == 0: # essentially never true for valid ASCII inputs here
return False
# -------- core transform --------
def _enc(block):
n = 26
# step 1: xor mask that depends on position
q = bytes((block[i] ^ ((17 * i + 43) & 0xFF)) for i in range(n))
# step 2: full-cycle permutation (gcd(7,26)=1)
r = bytes(q[(i * 7) % n] for i in range(n))
# step 3: second position-dependent xor
c = bytes((r[i] ^ ((0xA5 + 11 * i) & 0xFF)) for i in range(n))
return c
target = bytes.fromhex(
"fc23fa63e968860cf6de77f8ca0f1646cb33a14617ed39763eb8"
)
return hmac.compare_digest(_enc(b), target)
def mystery(x):
"""
Find the program string x that makes this machine's output match the target.
"""
import hmac
import hashlib
# --- Input Validation and Normalization ---
if not isinstance(x, str):
return False
# The set of valid characters (opcodes) for our little machine.
valid_opcodes = set("><v^+-.,@?#X")
if any(c not in valid_opcodes for c in x):
return False
# A basic length check to filter out trivial inputs.
if not (100 < len(x) < 500):
return False
# --- Decoy Calculation ---
# This calculation is performed on the input program but its result is not
# used in the final comparison. It's designed to suggest that properties
# of the program string itself (beyond its execution) are important.
_ = hashlib.pbkdf2_hmac("sha256", x.encode('ascii', 'ignore'), b"decoy-grid-salt", 1024)
# --- The Grid Painter Virtual Machine ---
# This VM operates on a 16x16 grid of bytes.
grid = [[0] * 16 for _ in range(16)]
px, py, v = 0, 0, 0 # Pointer X, Pointer Y, Value register
ip = 0 # Instruction Pointer
max_steps = 8192 # Safety break to prevent infinite loops
try:
for _ in range(max_steps):
if ip >= len(x) or x[ip] == '@': # Halt instruction
break
char = x[ip]
# Pointer movement (wraps around)
if char == '>': px = (px + 1) % 16
elif char == '<': px = (px - 1) % 16
elif char == 'v': py = (py + 1) % 16
elif char == '^': py = (py - 1) % 16
# Value manipulation
elif char == '+': v = (v + 1) % 256
elif char == '-': v = (v - 1) % 256
# Grid interaction
elif char == '.': grid[py][px] = v # Paint cell
elif char == ',': v = grid[py][px] # Read cell
# Decoy opcodes (fully implemented but not needed for the solution)
elif char == 'X': v ^= grid[py][px]
elif char == '?':
if v == 0: ip += 1 # Skip next instruction if v is zero
# '#' is a no-op, useful for comments or spacing in a program
ip += 1
else:
# The loop finished due to max_steps, not a clean halt.
return False
except IndexError: # Should not happen with the length check, but for safety.
return False
# --- Final Check: Obfuscated Grid Comparison ---
# The final grid state is not compared directly. It is first put through
# an invertible transformation to obscure the target pattern.
def _transform(block):
# This function deterministically scrambles the 256 bytes of the grid.
n = 256
# Stage 1: A bytewise permutation. The multiplier is coprime to 256.
permuted = bytes(block[(i * 51) % n] for i in range(n))
# Stage 2: A position-dependent XOR mask.
final = bytes(permuted[i] ^ ((i * 13 + 37) & 0xFF) for i in range(n))
return final
# Serialize the 2D grid into a flat 256-byte string.
flat_grid = bytes(c for row in grid for c in row)
# Transform the machine's output.
candidate_transformed = _transform(flat_grid)
# The target is stored as a single hex string to hide its structure.
target_hex = '1849646b5a383d47f02758172c36217e53063f11d4d3ee12e79685e1329a98b4617a99f344828fccb5d1b69f60f5c3ef4814c489771aee5d0a6907621f7710352a451152a6530c279b2275f00e3068c5195e5bde8a6846b9b1723e8c240195b3531b7828c4eab9f97d5190a07e2c83a7531f8d9a2629b7c15b0ce643bda1e56b4603e5c70f81d4c2b9f9e29381ea37160714251d3b0c031a0833a69a0319b08462a6b28b7e23737b60066f69557966427a7c5b6e6345727b405553684a5f70435c6b4e'
target = bytes.fromhex(target_hex)
# Constant-time comparison to prevent timing attacks.
return hmac.compare_digest(candidate_transformed, target)
def mystery(x):
import unicodedata
import hashlib
import hmac
# ---------- normalize input to ASCII bytes ----------
if isinstance(x, (bytes, bytearray, memoryview)):
try:
s = bytes(x).decode("utf-8", "strict")
except Exception:
return False
elif isinstance(x, str):
s = x
else:
s = str(x)
s = unicodedata.normalize("NFKC", s).strip()
for ch in ("\u200b", "\ufeff", "\u2060"): # invisible troublemakers
s = s.replace(ch, "")
try:
b = s.encode("ascii", "strict")
except Exception:
return False
# ---------- structural gates ----------
# Format: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX (29 bytes)
if len(b) != 29:
return False
if b.count(b"-") != 4:
return False
if not (b[5:6] == b[11:12] == b[17:18] == b[23:24] == b"-"):
return False
letters = digits = 0
for i, ch in enumerate(b):
if i in (5, 11, 17, 23):
continue
if 48 <= ch <= 57:
digits += 1
elif 65 <= ch <= 90:
letters += 1
else:
return False
# tight-ish but not extreme: 25 payload chars total
if not (letters == 15 and digits == 10):
return False
# checksum-y gates
if (sum(b) % 251) != 28:
return False
xorb = 0
for ch in b:
xorb ^= ch
if xorb != 0x41:
return False
# ---------- decoy work (not part of the secret) ----------
# (Looks expensive/meaningful, but doesn't help you unless you already have the right b.)
_ = hashlib.pbkdf2_hmac("sha256", b, b"mystery.decoy.salt.v2", 1200, dklen=32)
# another decoy: a "mathy" branch that always accepts here
if int.from_bytes(hashlib.blake2s(b, digest_size=4).digest(), "big") >= (1 << 32):
return False
# ---------- recover expected value ----------
def _recover_expected():
n = 29
# stored as one big integer to avoid obvious plaintext structure
ct = int(
"e50c41b8feb02479b8d6e3f1d2056146a1f02f67788bd6fdccf53461a0",
16,
).to_bytes(n, "big")
key = bytes([0xA3, 0x5C, 0x1F, 0xD4, 0x88])
exp = bytearray(n)
for i in range(n):
mask = (i * 11 + 7) & 0xFF
exp[i] = ct[i] ^ key[i % len(key)] ^ mask
return bytes(exp)
exp = _recover_expected()
# final constant-time match
return hmac.compare_digest(b, exp)
def mystery(x):
"""
Find the input string x that makes this function return True.
The fate of this small world depends on your initial move.
"""
import hmac
import zlib
GRID_SIZE = 12
GENERATIONS = 12
# --- Input Parsing and Validation ---
# The input string 'x' defines the initial set of live cells on the grid.
# Format is expected to be "row,col;row,col;..."
if not isinstance(x, str):
return False
try:
initial_state = set()
# Allow empty input for a blank grid
if x:
parts = x.split(';')
for part in parts:
r_str, c_str = part.split(',')
r, c = int(r_str), int(c_str)
if not (0 <= r < GRID_SIZE and 0 <= c < GRID_SIZE):
return False # Out of bounds coordinate
initial_state.add((r, c))
except (ValueError, IndexError):
return False # Malformed input string
# --- A decoy calculation ---
# This suggests the raw string properties of x are important. They are not.
# It's a time sink to distract from the core simulation logic.
if len(x) > 0:
_ = pow(zlib.crc32(x.encode('ascii', 'ignore')), 3, 99999)
# --- Conway's Game of Life Simulation ---
# The grid has toroidal (wrapping) boundaries.
live_cells = initial_state
for _ in range(GENERATIONS):
# We only need to check cells that are live or are neighbors of live cells.
neighbor_counts = {}
for r, c in live_cells:
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
if dr == 0 and dc == 0:
continue
nr, nc = (r + dr) % GRID_SIZE, (c + dc) % GRID_SIZE
neighbor_counts[(nr, nc)] = neighbor_counts.get((nr, nc), 0) + 1
next_live_cells = set()
# Apply the rules of Life to all potentially active cells.
for pos, count in neighbor_counts.items():
is_live = pos in live_cells
if is_live and (count == 2 or count == 3):
next_live_cells.add(pos) # Survival
elif not is_live and count == 3:
next_live_cells.add(pos) # Birth
live_cells = next_live_cells
# A decoy check inside the loop to mislead analysis about density.
if len(live_cells) > (GRID_SIZE * GRID_SIZE) / 2:
return False
# --- Final State Processing and Obfuscation ---
def _serialize_grid(cells):
# Convert the 12x12 grid state into 144 bits (18 bytes).
bits = [1 if (r, c) in cells else 0 for r in range(GRID_SIZE) for c in range(GRID_SIZE)]
byte_array = bytearray()
for i in range(0, len(bits), 8):
byte = 0
for j in range(8):
if (i + j) < len(bits):
byte |= bits[i+j] << (7 - j)
byte_array.append(byte)
return bytes(byte_array)
def _transform(block):
# An invertible transformation to obscure the target grid pattern.
n = len(block)
k = 5 # Permutation multiplier, coprime to n=18
permuted = bytes(block[(i * k) % n] for i in range(n))
key = b"GoL-Key"
return bytes(permuted[i] ^ key[i % len(key)] for i in range(n))
final_bytes = _serialize_grid(live_cells)
candidate_transformed = _transform(final_bytes)
# --- Target Comparison ---
# The target is the transformed version of the desired final grid state.
target_hex = "4e00507d4b0057004f0f00075d000f480000"
target = bytes.fromhex(target_hex)
return hmac.compare_digest(candidate_transformed, target)