Challenge Description

Category: Reverse Engineering / Industrial Control

Difficulty: 🔴 Hard

The cartridge simulates a Clearwater tank-farm shift. Pump P-101 fills the break tank, FCV-2 supplies the distribution network, and demand changes throughout the shift. Complete 60 seconds without tripping the plant and submit the operator token.

The attachment is the same 32 KiB waterworks.gb cartridge used by the other Clearwater training-rig challenges. This time the task looks less like reversing and more like playing a tiny process-control game.

The HMI gives us two controls:

  • A toggles pump P-101;
  • B toggles valve FCV-2.

It also gives us a reassuringly wide safe band of 30–70%. Keep the tank in that band for one minute. Easy, right?

Waterworks Game Boy HMI during a running operator shift

My first instinct was to play by eye: switch the pump on when the level falls, shut the valve if it falls too quickly, and correct whatever the next screen update shows. That approach misses almost everything interesting in the ROM.

The displayed level is only the integer part of a process with hidden fractional momentum. Demand changes every few seconds. Closing the valve reduces tank outflow but creates a separate no-supply path. Alarms have dwell time rather than tripping immediately. A control decision that looks safe now can already have enough accumulated state behind it to cross a boundary later.

The reliable solution was to stop treating the HMI as a game and reverse it as a controller.


TL;DR

  • A new shift begins at tank level 50, with P-101 off and FCV-2 open
  • A toggles the pump; B toggles the valve; Start aborts
  • Pump supply is 48 model units per frame
  • Demand follows a 16-entry table and advances every 180 frames
  • Closing FCV-2 divides outflow by four but arms a no-supply condition under high demand
  • Tank high alarm: level >= 71
  • Tank low alarm: level < 30
  • A persistent alarm trips the plant after 180 alarm frames
  • The shift completes after 60 groups of 60 frames
  • A stable policy is to leave FCV-2 open and toggle P-101 on at 40%, off at 60%
  • A tested PyBoy run lasts exactly 3,600 process frames, remains in the range 40–60, and ends at 54%
  • The completion token is:
flag{shift_complete_operator001}

Cartridge Triage

The ROM header gives us a pleasantly simple target:

Title          WATERWORKS
Size           0x8000 / 32768 bytes
Cartridge      ROM ONLY (type 0x00)
Banking        none
External RAM   none
Header check   0x9A, valid
SHA-256        41f2bcb3c80267cc7de348ce06c7dfb4ebfbd375a163d1e70d707e9c59e4bef4

There is no memory-bank controller. Every ROM address below 0x8000 is also the corresponding file offset, which makes cross-referencing code and data much less painful.

Following the entry point and main loop produced this gameplay map:

Address Role
0x0150 Hardware and application initialization
0x018A Main loop
0x01FB Joypad edge scanner
0x0272 Initialize a new shift
0x02A1 Handle operator controls
0x02F1 Compute supply/outflow difference
0x0318 Fetch current demand-table value
0x0324 Apply positive tank delta
0x0344 Apply negative tank delta
0x0361 Advance demand every 180 frames
0x0379 Classify alarms and enforce trip dwell
0x03E3 Advance the 60-second shift clock
0x0680 Shift-complete screen
0x0778 Completion-token decoder
0x07C4 Sixteen-entry demand curve
0x0A8E Encrypted completion token

The main loop is organized almost like a small PLC scan:

wait for frame boundary
read operator input
update process model
advance demand profile
evaluate alarms/interlocks
advance shift timer
update HMI
repeat

That structure is why reversing the individual state bytes is more useful than trying to infer behavior from the screen alone.


Reconstructing WRAM

The gameplay routines use a contiguous block beginning at C000. Naming those bytes was the turning point:

Address Meaning
C000 Currently held joypad mask
C001 Newly pressed joypad edges
C002 State: 0 title, 1 running, 2 complete, 3 tripped, 4 service
C003 Service-sequence progress
C004 UI/frame counter
C005 Integer tank level
C006 Fractional tank accumulator
C007 Pump P-101 state
C008 Valve FCV-2 state
C009 Demand-table index
C00A Demand frame counter, 0..179
C00B Alarm code: 0 nominal, 1 high, 2 low, 3 no supply
C00C Common alarm dwell counter
C00D Elapsed shift seconds
C00E Subsecond frame counter, 0..59
C00F No-supply qualification counter
C010 Screen redraw request

The new-shift routine at 0x0272 clears the process block, then installs the three visible initial conditions:

0272  xor  a
0273  ld   ($C006),a      ; fractional accumulator = 0
0276  ld   ($C007),a      ; pump = OFF
0279  ld   ($C009),a      ; demand index = 0
027C  ld   ($C00A),a      ; demand frame counter = 0
027F  ld   ($C00B),a      ; alarm = NOMINAL
0282  ld   ($C00C),a      ; alarm dwell = 0
0285  ld   ($C00D),a      ; elapsed seconds = 0
0288  ld   ($C00E),a      ; subsecond frames = 0
028B  ld   ($C00F),a      ; no-supply counter = 0

028E  ld   a,$32
0290  ld   ($C005),a      ; tank level = 50
0293  ld   a,$01
0295  ld   ($C008),a      ; valve = OPEN
0298  ld   ($C010),a      ; request redraw
029B  ld   a,$01
029D  ld   ($C002),a      ; state = RUNNING
02A0  ret

This also resolves a small UI ambiguity: 1 means open/on for both actuator bytes. The pump starts at zero; the valve starts at one.


Controls Are Edges, Not Held Levels

The input handler at 0x02A1 reads newly pressed bits from C001, not the held mask in C000:

02A1  ld   a,($C001)
02A4  bit  4,a            ; A button
02A6  jr   z,$02B3
02A8  ld   a,($C007)
02AB  xor  $01
02AD  ld   ($C007),a      ; toggle P-101

02B3  ld   a,($C001)
02B6  bit  5,a            ; B button
02B8  jr   z,$02C5
02BA  ld   a,($C008)
02BD  xor  $01
02BF  ld   ($C008),a      ; toggle FCV-2

02C5  ld   a,($C001)
02C8  bit  7,a            ; Start
02CA  jr   z,$02D6
02CC  xor  a
02CD  ld   ($C002),a      ; abort to title
02D0  ld   a,$01
02D2  ld   ($C010),a

Holding A does not oscillate the pump every frame. One press generates one rising edge and one toggle. This becomes important later when automating the controller with PyBoy.


The Demand Curve Hiding Beside the Code

The demand lookup at 0x0318 is a direct indexed read:

0318  ld   a,($C009)
031B  ld   e,a
031C  ld   d,$00
031E  ld   hl,$07C4
0321  add  hl,de
0322  ld   a,(hl)
0323  ret

At 0x07C4, the ROM stores:

10 12 18 14 1e 24 2c 34 28 1e 16 12 22 32 1a 14

In decimal:

16, 18, 24, 20, 30, 36, 44, 52,
40, 30, 22, 18, 34, 50, 26, 20
Recovered sixteen-step network-demand table

The routine at 0x0361 increments C00A once per process frame. At 0xB4 = 180, it resets the counter and advances C009 modulo 16:

if (++demand_frames == 180) {
    demand_frames = 0;
    demand_index = (demand_index + 1) & 0x0f;
}

At 60 frames per second, demand changes every three seconds. The sixteen entries cover 48 seconds and then wrap for the final 12 seconds of the shift.

The peak is 52, just above the pump’s fixed capacity of 48. That is a good piece of challenge design: the highest instantaneous demand tells us the tank will sometimes fall even with P-101 on, but it does not justify leaving the pump on. Across most of the curve, 48 is far more supply than the network consumes.


Reversing the Mass-Balance Model

The process calculation begins at 0x02F1:

supply = 0
if pump_on:
    supply = 48

outflow = demand[demand_index]
if valve_closed:
    outflow >>= 2

Then the routine compares supply and outflow and sends the unsigned difference to one of two helpers:

if (supply >= outflow)
    add_to_tank(supply - outflow);
else
    remove_from_tank(outflow - supply);

The important detail is that the difference does not directly change the integer percentage at C005. It first changes the 8-bit accumulator at C006.

Positive path, simplified from 0x0324:

sum = fraction + delta;
fraction = sum & 0xff;

if (sum > 0xff) {
    level++;
    if (level > 100) {
        level = 100;
        fraction = 0xff;
    }
}

Negative path, simplified from 0x0344:

borrow = fraction < delta;
fraction = (fraction - delta) & 0xff;

if (borrow) {
    if (level > 0)
        level--;
    else
        fraction = 0;
}

A readable model is therefore:

fraction += supply - outflow

while fraction >= 256:
    level += 1
    fraction -= 256

while fraction < 0:
    level -= 1
    fraction += 256
Reconstructed supply, demand, and hidden fractional tank model

This hidden byte is why pixel-watching is weaker than state-aware control. A displayed level of 60 can mean 60 + 0/256 or 60 + 255/256. Those states look identical but cross to 61 at very different times.

Closing FCV-2 shifts outflow right twice, effectively dividing it by four. That looks like an emergency way to preserve the tank. It is, but only if the distribution side is ignored. The next routine does not ignore it.


Alarm Logic and the Delayed Trip

The alarm classifier at 0x0379 clears C00B and then applies the level thresholds:

level >= 0x47 (71)  -> alarm 1, LEVEL HIGH
level <  0x1E (30)  -> alarm 2, LEVEL LOW

Notice the exact boundaries. The HMI says the safe band is 30–70%. The assembly agrees: 30 and 70 are safe; 29 and 71 are not.

The no-supply path checks FCV-2 separately:

if (!valve_open && raw_demand >= 30) {
    if (no_supply_counter < 200)
        no_supply_counter++;

    if (no_supply_counter >= 180)
        alarm = 3;
} else {
    no_supply_counter = 0;
}

This means the one-quarter outflow shortcut is not free. During high raw demand, a closed valve first accumulates its own qualification timer. Once alarm 3 is active, the common alarm dwell begins accumulating too.

For any active alarm, C00C increments. At 180 alarm frames the ROM switches to state 3:

C002 = 3     PLANT TRIPPED
C010 = 1     redraw

If conditions return to normal before the trip, the common dwell counter decays one count per frame rather than resetting instantly. That is another small piece of process realism hidden behind the simple display.

My initial “shut the valve if the tank falls” instinct was therefore the wrong control objective. It protects inventory by withholding supply from the simulated network, and the program explicitly monitors that failure mode.


The Shift Clock

The timer at 0x03E3 is independent of the demand timer:

03E3  ld   a,($C00E)
03E6  inc  a
03E7  ld   ($C00E),a
03EA  cp   $3C            ; 60 frames
03EC  ret  c

03ED  xor  a
03EE  ld   ($C00E),a
03F1  ld   a,($C00D)
03F4  inc  a
03F5  ld   ($C00D),a
03F8  cp   $3C            ; 60 seconds
03FA  ret  c

03FB  ld   a,$02
03FD  ld   ($C002),a      ; SHIFT COMPLETE
0400  ld   a,$01
0402  ld   ($C010),a
0405  ret

The target is exactly 60 groups of 60 process frames: 3,600 frames in running state.


Deriving a Stable Controller

Once the model is written down, the safe strategy is deliberately boring:

  1. leave FCV-2 open for the entire shift;
  2. turn P-101 on when level reaches 40%;
  3. turn P-101 off when level reaches 60%.

This is a two-point hysteresis controller. The 20-point deadband prevents rapid toggling, keeps inventory ten points away from either alarm boundary, and never sacrifices distribution flow.

I first validated it in a small model before touching the emulator:

demand = [
    16, 18, 24, 20, 30, 36, 44, 52,
    40, 30, 22, 18, 34, 50, 26, 20,
]

level = 50
fraction = 0
pump = False
demand_index = 0
demand_frames = 0

for frame in range(60 * 60):
    if level <= 40:
        pump = True
    elif level >= 60:
        pump = False

    supply = 48 if pump else 0
    outflow = demand[demand_index]   # valve remains open

    if supply >= outflow:
        total = fraction + (supply - outflow)
        fraction = total & 0xff
        if total > 0xff:
            level += 1
    else:
        delta = outflow - supply
        borrow = fraction < delta
        fraction = (fraction - delta) & 0xff
        if borrow:
            level -= 1

    demand_frames += 1
    if demand_frames == 180:
        demand_frames = 0
        demand_index = (demand_index + 1) & 0x0f

assert 30 <= level <= 70
print(level)
54

The simulated level remains between exactly 40 and 60. Approximate pump transitions are:

ON   02.42s   OFF 05.10s
ON   08.73s   OFF 11.68s
ON   14.50s   OFF 27.68s
ON   30.53s   OFF 33.58s
ON   37.13s   OFF 44.80s
ON   49.02s   OFF 51.60s
ON   55.60s   OFF 58.72s

The long middle ON interval lines up with the sustained high-demand section containing 36, 44, 52, 40 and the later 34, 50 pair.

Hysteresis controller holding the tank safely between 40 and 60 percent

This is the point where the challenge stopped looking like button timing and started looking like a small, recognizable control problem.


Validating the Policy Against the Real ROM

The model explains the strategy, but I still wanted the unmodified cartridge to execute all 3,600 frames and render the reward itself.

The following script was tested with PyBoy 2.8.1:

from pyboy import PyBoy

STATE = 0xC002
LEVEL = 0xC005
PUMP = 0xC007
VALVE = 0xC008
SECONDS = 0xC00D

gb = PyBoy("waterworks.gb", window="null", sound_emulated=False)
gb.set_emulation_speed(0)

# Finish boot and the first title redraw.
gb.tick(120, render=False, sound=False)
assert gb.memory[STATE] == 0

# button() is a one-frame press followed by an automatic release.
gb.button("start")
gb.tick(2, render=False, sound=False)

assert gb.memory[STATE] == 1
assert gb.memory[LEVEL] == 50
assert gb.memory[PUMP] == 0
assert gb.memory[VALVE] == 1

frames = 0
minimum = 100
maximum = 0

while gb.memory[STATE] == 1:
    level = gb.memory[LEVEL]
    pump = gb.memory[PUMP]

    minimum = min(minimum, level)
    maximum = max(maximum, level)

    # Keep FCV-2 open. Toggle P-101 at the hysteresis limits.
    if (level <= 40 and pump == 0) or (level >= 60 and pump != 0):
        gb.button("a")

    gb.tick(1, render=False, sound=False)
    frames += 1

    if frames > 3700:
        raise RuntimeError("shift did not terminate")

assert frames == 3600
assert gb.memory[STATE] == 2
assert gb.memory[SECONDS] == 60
assert minimum == 40
assert maximum == 60
assert gb.memory[LEVEL] == 54

# Render the completion screen. Font tile zero is ASCII space.
gb.tick(3, render=False, sound=False)
tiles = (
    bytes(gb.memory[0x9922:0x9932])
    + bytes(gb.memory[0x9942:0x9952])
)
token = bytes((tile + 0x20) & 0xff for tile in tiles).decode("ascii")
print(token)

gb.stop(save=False)
flag{shift_complete_operator001}

The final assertions are not decorative. They verify that the real ROM:

  • stayed in running state for exactly 3,600 frames;
  • reached completion state 2 rather than trip state 3;
  • counted exactly 60 seconds;
  • never left the 40–60 band;
  • ended at level 54;
  • rendered the expected token into its own tile map.
Shift complete screen and recovered operator token

PyBoy’s Button API Can Eat the Start Press

The 120-frame warm-up in the script is not arbitrary. During early boot and the first title redraw, the program is not yet executing its normal joypad path. Sending Start too early lets PyBoy press and release it before 0x01FB samples the edge.

There are two correct ways to drive a button:

# Convenience API: pressed on the next tick, automatically released after it.
gb.button("start")
gb.tick(2)

# Persistent API: release it explicitly, but only after a pressed tick.
gb.button_press("start")
gb.tick(1)
gb.button_release("start")
gb.tick(1)

This form is wrong for an edge-triggered ROM:

gb.button("start")
gb.button_release("start")
gb.tick(2)

I tested it. The press and release collapse before the ROM observes the edge, C001 remains clear, and the cartridge stays on the title screen.

The same rule applies to every pump toggle. button("a") already creates the required press/release pair. Adding an immediate manual release makes the controller appear to run while silently dropping commands.


Following the Reward Path

Reaching state 2 dispatches to the shift-complete renderer at 0x0680. The fixed strings say:

SHIFT COMPLETE
TANK HELD IN BAND
FOR THE FULL SHIFT.
SHIFT TOKEN:

The token itself is not stored as plaintext. The renderer points HL at 0x0A8E, initializes C = 0xB7, and calls 0x0778 twice for two 16-character rows.

0778  ld   a,(hl+)        ; ciphertext byte
0779  xor  c              ; plaintext ASCII
077A  sub  $20            ; ASCII -> font tile index
077C  ld   (de),a
077D  inc  de
077E  ld   a,c
077F  rlca                ; rotate key left by one bit
0780  add  a,$13
0782  ld   c,a            ; next key
0783  dec  b
0784  jr   nz,$0778
0786  ret

The SUB 0x20 is display conversion, not encryption. Before that subtraction, the plaintext relation is:

plaintext[i] = ciphertext[i] XOR key
key          = ROL8(key, 1) + 0x13 mod 256
initial key  = 0xB7

Static Token Recovery

The 32 ciphertext bytes at 0x0A8E–0x0AAD can also be decoded directly:

from pathlib import Path

rom = Path("waterworks.gb").read_bytes()
cipher = rom[0x0A8E:0x0AAE]

key = 0xB7
plain = bytearray()

for byte in cipher:
    plain.append(byte ^ key)
    key = ((((key << 1) | (key >> 7)) & 0xff) + 0x13) & 0xff

print(plain.decode("ascii"))
flag{shift_complete_operator001}

There are therefore two complete solution paths:

  • reverse the process and operate the real ROM safely for 60 seconds;
  • follow the completion renderer and recover the reward statically.

I prefer doing both. The first validates the control model. The second proves that the token extracted from VRAM is generated by the decoder we identified rather than being a fortunate screen scrape.


Flag

flag{shift_complete_operator001}

Reflection

The nicest part of this challenge is that the rolling-XOR flag decoder is not the hard part. The real challenge is recognizing a credible control loop inside a Game Boy ROM:

  • fixed pump capacity;
  • time-varying network demand;
  • an actuator that trades tank retention for service loss;
  • fractional state hidden behind an integer display;
  • alarm qualification and persistence rather than instant failure;
  • a finite operating horizon.

The first tempting “fix” is to close the valve when inventory falls. The ROM punishes that because a treatment plant is not successful merely because its own tank remains full; it must keep supplying the network. The second tempting fix is to leave the pump on. The demand table punishes that with a high-level trip.

The final solution is exactly what I would want from a small real controller: keep the downstream path available and apply hysteresis around the inventory target.

Reverse engineering told me what the plant was doing. A simple control policy told me what to do back. PyBoy then proved that both interpretations were correct for every frame of the actual cartridge.