aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


commit c983841a88a6fb9121b3f7a8bd8b0ac2fe15483d
parent 046f2b5b9e3cd9d06fb572ee532c45bc6f322dfa
Author: anon <anon@example.com>
Date:   Tue, 27 Oct 2026 07:06:58 +0000

Retire starter missions atomically on abandonment and expiry

Handle native QuestIIR removal and QuestEvent expiry through one contract/key
retirement transaction. Cover every key location, copied bindings and affected
draft trades; keep future deadlines in memory and retire overdue contracts on
startup without rewards.

Add failure, replay, concurrency and storage regressions plus native WASM
verification. Record provisional key policy and the remaining expiry-waypoint
and intermittent terminal-abort investigations.

Diffstat:
MTODO.md | 47+++++++++++++++++++++++++++++++++++++++--------
Mdocs/mission-acceptance.md | 9+++++----
Adocs/mission-retirement.md | 138+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/item_database.go | 6++++++
Mserver/item_store.go | 1+
Mserver/main.go | 4++++
Aserver/mission_retirement.go | 257+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_retirement_test.go | 546+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/missions.go | 2++
Mserver/roaming.go | 1+
Mserver/state.go | 1+
Mserver/users.go | 3+++
12 files changed, 1003 insertions(+), 12 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -57,8 +57,9 @@ Bio-Comminutor from basic pharmacy stock. Native crafting, cancelled sale, cold recovery and accepted sale passed with an earned part and controlled tool funds; ordinary funding and higher-QL recipe rules remain open. See [Blood Plasma](docs/blood-plasma.md). -Complete quest and mission progression remains open; opening a booth and browsing -an offer do not yet provide accepted contracts, objectives or mission rewards. +Starter mission contracts can now be browsed, accepted, abandoned and expired, +with durable journals and bound keys. Private interiors, objectives and mission +rewards remain open. After fixing an inactive-mesh projectile that blocked repeated native casts, a fresh Atrox Nano-Technician completed fifteen ordinary Leet kills without a death, reaching level 2 with 1500 cumulative XP and exactly 4000 new IP. @@ -1389,6 +1390,8 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). Introduce explicit instance isolation across visibility, combat, nanos, loot, inspection, trading and vicinity chat. Persist significant assignment/return transitions immediately; ordinary periodic position checkpoints are insufficient. + Include private-instance retirement on abandonment/expiry without affecting + another owner's assignment or admitting holders of revoked key bindings. - [ ] [P1] Complete mission-key destination metadata and duplication. Check: keys identify their assigned destination in the native UI, copies retain the same assignment, and door admission follows actual key-instance bindings. @@ -1406,12 +1409,30 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). trigger remains unverified. The original offer details qualify XP with "Which you get when you receive a token." Establish that rule before settling rewards; an arbitrary copy of the objective item must not complete a contract. -- [ ] [P1] Abandon that mission. Check: its journal entry and private assignment are - removed without affecting another character's mission. -- [ ] [P1] Expire an accepted mission. Check: its saved deadline drives native - remaining time and authoritative contract/key/instance retirement across - offline time and restart. Current replay shows remaining time, but the server - does not yet retire the contract; a stale contract must not block new missions. +- [x] Abandon an accepted starter contract. Check: the native journal and bound + key instances retire atomically without rewards or changes to another owner's + contract. Native QuestIIR/version1/action5 follows the original RemoveQuest + request and consumer. GPU WASM verifies both confirmation choices, removal + from open inventory/journal, waypoint clearing and acceptance of the next mission. +- [x] Expire an accepted starter contract. Check: its saved deadline retires the + contract and bound keys online, offline and on startup. No database writes occur + before the deadline; failed writes/commit retain it for retry. Go tests cover + all key locations, copied bindings, pending trades, stale/foreign/repeated + requests, concurrent expiry/abandonment and output failure. Native WASM verifies + online expiry and empty inventory/journal after a cold server restart. + Private-instance cleanup remains part of the entry/instance work above. + See [mission retirement](docs/mission-retirement.md). +- [ ] [P2] Retire uploaded waypoints when their mission expires. Native + QuestEvent1 now reports "Quest expired.." and removes the journal/key, but the + GPU local map retains the white X until reconnect. The original expiry + consumer0x3606c060 emits the explicit waypoint-clear UI event only for completion + event2. Trace waypoint ownership/lifetime before changing the client; never + send a false completion event to clear the marker. Captures and original + evidence: `local/mission-retirement/event-expiry-*` and the retirement notes. +- [ ] [P2] Establish original14.9.1 key retention/removal on abandonment and copied + keys held elsewhere. Current immediate bound-key deletion on abandonment is + provisional; original client journal behavior does not prove server key policy. + Preserve the documented distinction between period and later secondary evidence. - [ ] [P1] Generate one two-room mission layout. Check: a fixed test seed produces connected rooms with a reachable entrance, objective and exit. - [ ] [P1] Apply difficulty and all six mission dimensions to generated content. @@ -2292,6 +2313,16 @@ current SQLite storage when applying these findings. ## Thorough gameplay regression testing +- [ ] [P0] Reproduce and diagnose the intermittent WASM abort while opening the + starter mission terminal. One owned GPU run stopped before generation or + acceptance with ErrorEvent/Aborted and an empty "Stopped:" reason. A cold + same-binary retry opened the booth and accepted normally; five subsequent + isolated cold terminal-opening runs also passed. Preserve full native + console output and worker error details; the initial recorder omitted + console.log, including Module.printErr. Its last sampled BBR function is not + a crash stack or proof of a missing adapter. Captures/profile: + `local/mission-retirement/event-crash-*`; successful retry: + `local/mission-retirement/event-retry-*`. - [ ] [P3] Reproduce stale shop interaction state after a live control-panel inventory edit. In the restoration smoke run, a nearby original terminal reported "Too far away" after the edit, while a fresh page could use it. diff --git a/docs/mission-acceptance.md b/docs/mission-acceptance.md @@ -91,7 +91,8 @@ screenshots and exact accounting are retained in `local/mission-acceptance/`. Private destination assignment and entry remain the next integration. The saved exterior entrance is not a private world instance. Do not admit players until visibility, simulation and interaction consumers have explicit instance scope. -Expiry currently supplies remaining native time; server expiration/removal, -abandonment, key duplication/metadata and objective completion/rewards remain -open in TODO.md. The fixed narrative, reward values and48-hour duration remain -provisional as documented in [mission offers](mission-offers.md). +Saved deadlines now drive [retirement](mission-retirement.md), including native +abandonment and bound-key cleanup. Key duplication/metadata and objective +completion/rewards remain open in TODO.md. The fixed narrative, reward values +and48-hour duration remain provisional as documented in +[mission offers](mission-offers.md). diff --git a/docs/mission-retirement.md b/docs/mission-retirement.md @@ -0,0 +1,138 @@ +# Mission abandonment and expiry + +Accepted starter contracts can be abandoned through the native mission journal +and expire at their saved deadline. Both use one retirement transaction: remove +the contract and every item instance bound to it, then publish inventory changes +and the native journal removal. Retirement grants no credits, XP or completion +rewards. It frees the one-training-mission limit for the next assignment. + +## Native request and reply + +Original14.9.1 `kkr.dll`, SHA256 +`241b2e665dcd127399b7686cddda8a5b0876d9cde9b3af7a73940dd0b86ecaa7`, +exports `N3Msg_RemoveQuest` at0x36021260. It constructs QuestIIR through +0x36080960 with the local character subject, action5, the selected quest identity +and a zero secondary identity. It has no character-life or terminal-range gate. +The reader0x36080a70 and writer0x36080ae0 carry DWORD version1, DWORD action +and two identities. The version constant at0x361c5058 is1; the secondary +identity global at0x362ea510 is zero. + +Apply0x36080b30 resolves the character and calls0x3606c180. Action5 dispatches +to0x3606be30, which removes the quest from native object/journal lists, refreshes +the UI and destroys the quest object. The request also calls0x3601cb20 to send +the local quest UI event0x2c. The server handles the owner-authenticated +QuestIIR0x212c487a request and replies with the same action5 and quest identity. +Malformed versions, actions, identity types, nonzero secondary identities, +foreign contracts, stale sessions and clients still loading cannot retire it. + +Expiry uses the distinct QuestEventIIR0x5f2e1b19: DWORD version1, quest identity, +DWORD event1. Its registered factory0x36010220 constructs0x360c6b00; the native +reader0x360c6b70 and writer0x360c6bd0 establish the field order, with version1 +at0x361c91cc. Apply0x360c6c10 lacks a Ghidra function boundary, but decoded +calls at0x360c6c49/0x360c6c50 and the maintained lifted body resolve the +character's quest holder and call0x3606c060. That consumer activates the quest +argument and distinguishes event1 ("Quest expired..") from event2 ("Mission +accomplished!"). Expiry must not send completion event2. + +Expiry reader/writer evidence is +`ev_61c9e52c8bd23b82de9a7df8c98ee7662cb120be22b913f2eab8ef9e4d652225` and +`ev_1a00dde46f203cbde2c7592e81add191bf1c46179f91abd70eaff375671d773d`; +the version constant is +`ev_40dc948f4e8ff4bb016729a51f37ece1d0b006ad182247b73f65b5d7ee64032a`. +The expiry/completion consumer is +`ev_9dedfeb8baf538c25f3c8042b20a1eecc931b24a9e56dc3c4e1cafd89fb19198`. +The decoded Apply calls are +`ev_fb426f67ee0e122c0d1a31239b65c9429ee67d33e8fb73d4f9b84503c914dbcc` and +`ev_4489436752dc5bed6b6d8b173ce8b94293d6599cddbf93c12d8f62a29acd3442`. + +REA evidence IDs: + +- RemoveQuest: `ev_1b4e1d5708b0289c6ffd162b12cc87bf4448c736b0f04ca6800eb09dbe2a3ab4`. +- Constructor: `ev_51614f94a9d14d04ad94058b4d570d25bbdfafb22876b6fb10af6f536514db95`. +- Reader/writer: `ev_25279233a02cdc523a81c477a17e382d34face2de6ee71ba4ca1ef694c13bc02`, + `ev_af959fa929bf52d45f56b126a7f79dc28ff4fad88f838c828f66e4a8c7fb0dba`. +- Apply/dispatch: `ev_7d8e204d21b3ebd2e211ab9bf294912bd87fcfa7dcfc19cee7d4c1e0efe30bcc`, + `ev_b06b28b3d8e1b0225b3ba1cc16d78e828242a0e058d6847b9672cd9bc6871a47`. +- Removal consumer: `ev_0dcb94ee3268743da29926bd8938e0c94d230fef76f4acb7e67656ea72d983e5`. + +The complete evidence snapshot is retained in +`local/mission-retirement/kkr-evidence.json`. + +## Ownership and transaction boundaries + +`mission_keys` binds actual instances, including any copies held by other +characters. Retirement removes only those IDs. Unrelated template28577 keys, +Blue Books, equipment, cash and XP remain intact. Inventory, bank, backpack, +reclaim, corpse and unassigned locations participate in the same transaction. +The original receipt tip explicitly says keys can enter reclaim after death; +death alone does not retire a mission. + +Affected shop/player trade drafts are restored in native first-free order in +the candidate inventory before removing their keys. Drafts are cleared only +after commit. Late acceptance or cancellation cannot restore or sell a retired +key. Open placement views receive their matching removal/update packets; +reclaim snapshots keep stable indices. No live container aliases or client +messages change before the transaction commits. + +The expiry index contains accepted contracts rather than scanning all NPCs each +tick. Checking a future deadline performs no database writes. A due retirement +uses the same transaction even while its owner is offline. Startup retires +already expired contracts before accepting clients. A failed write/commit +preserves the pending contract for retry; successfully retired earlier entries +still publish their updates if a subsequent expiry fails. Lost client output +after commit cannot restore the durable contract or key. + +## Evidence limits and remaining work + +Lifecycle tests cover native socket abandonment, malformed/foreign/stale +requests, repeated and concurrent retirement, exact deadlines, offline/startup +expiry and retries. Deletion fault injection covers items, placements, contracts +and cascading key bindings, including ignored writes and deferred commit errors. +Placement failures preserve live container aliases. Additional cases cover +bank/backpack/reclaim views, corpse loot, offline holders, copied bindings, +unassigned keys, draft trades and late trade packets, partial expiry batches, +output failure, and abandonment by a dead owner away from a terminal. Concurrent +generation, acceptance and abandonment/expiry pass the race detector. + +GPU Chromium tests exercise native confirmation cancellation/acceptance, +ordinary key/journal/waypoint removal, acceptance of a subsequent assignment, saved +deadline expiry and cold recovery without the retired key/journal. Wire +validation corroborates both message hashes and the exact quest identities; +expiry reports "Quest expired.." through event1. Fixture funds are controlled, +not earned-income proof, and no completion reward is granted. Captures, exact +accounting and `wire-validation.json` are in `local/mission-retirement/`. +The final binary was also checked through both abandonment confirmation choices; +five controlled generation fees left level1/XP0 and zero credits. Only the owned +test character was removed afterward, with unrelated-row hashes and SQLite +foreign-key/integrity checks preserved. + +Native expiry still leaves an uploaded white waypoint visible until reconnect. +The recovered consumer explicitly emits waypoint-clear UI event0x2c for +completion event2, not expiry event1. This does not establish the original +server's complete notification sequence. Keep the UI cleanup gap open rather +than sending a false completion event. + +One terminal-opening run aborted before generation/acceptance, with no useful +stack retained by its initial recorder. The recorder now captures native +stdout/stderr and error details. Five subsequent isolated cold terminal runs +passed, but they do not establish a fix or identify the cause. The failed +profile's last sampled BBR function is not a crash stack. This remains a P0 +diagnostic follow-up in TODO.md. Successful retirement runs have no page +exceptions; unattributed HTTP404 console messages also occur on successful +runs. No adapter/runtime change is justified by the retained abort evidence. + +Immediate bound-key deletion on abandonment is a provisional server policy. +The original client proves journal removal, but does not establish the original +server's abandonment key policy. The local AOWiki `Missions` page, touched in2021, +describes key disappearance on completion/expiry; this is later secondary +evidence. A January2002 player report also describes completion removing the +mission key and other mission items, without establishing abandonment behavior: +[period report](https://forums-archive.anarchy-online.com/showthread.php?9198-Overflow-inventory=). +Do not treat these as proof for14.9.1 abandonment or copied-key edge cases. + +Private interior allocation/entry and objective completion remain unimplemented. +Their eventual instance lifecycle must join retirement; the current contract's +exterior entrance is not a private world instance. Destination metadata and +native key duplication also remain open. The fixed narrative, rewards and +48-hour duration remain provisional as documented in +[mission offers](mission-offers.md). diff --git a/server/item_database.go b/server/item_database.go @@ -182,6 +182,12 @@ func (server *server) persistItems_locked(store itemStore) error { return err } } + if store.removedMission != nil { + var removed uint32 + if err := tx.QueryRow("DELETE FROM missions WHERE id=? AND owner_id=? RETURNING id", store.removedMission.id, store.removedMission.owner).Scan(&removed); err != nil { + return fmt.Errorf("remove mission %d: %w", store.removedMission.id, err) + } + } if store.skillLock != nil { if err := writeSkillLock(tx, store.skillLock.Player, store.skillLock.Skill, store.skillLock.Until); err != nil { return err diff --git a/server/item_store.go b/server/item_store.go @@ -53,6 +53,7 @@ type itemStore struct { vitalUpdate *playerVitalUpdate skillLock *skillLockUpdate mission *acceptedMission + removedMission *acceptedMission inventoryPlayers []uint32 checkpointAt time.Time flush bool diff --git a/server/main.go b/server/main.go @@ -495,6 +495,10 @@ func (server *server) serveWorldClient(client *worldClient) error { decodeInventory1491(body) } switch binary.BigEndian.Uint32(body[0:4]) { + case 0x212c487a: + if err := server.handleMissionRemoval(client, body); err != nil { + return err + } case 0x291f361b: if err := server.handleMissionAcceptance(client, body); err != nil { return err diff --git a/server/mission_retirement.go b/server/mission_retirement.go @@ -0,0 +1,257 @@ +package main + +import ( + "encoding/binary" + "log" + "maps" + "slices" + "time" +) + +func missionRemovalPacket(owner, id uint32) []byte { + var body []byte + for _, word := range []uint32{1, 5, 56003, id, 0, 0} { + body = binary.BigEndian.AppendUint32(body, word) + } + return n3Packet(0x212c487a, 50000, owner, body) +} + +func missionExpiryPacket(owner, id uint32) []byte { + // QuestEvent1 activates the original expired event before removing the journal. + var body []byte + for _, word := range []uint32{1, 56003, id, 1} { + body = binary.BigEndian.AppendUint32(body, word) + } + return n3Packet(0x5f2e1b19, 50000, owner, body) +} + +func (server *server) handleMissionRemoval(client *worldClient, body []byte) error { + if len(body) != 40 || binary.BigEndian.Uint32(body[16:20]) != 1 || binary.BigEndian.Uint32(body[20:24]) != 5 || + binary.BigEndian.Uint32(body[24:28]) != 56003 || binary.BigEndian.Uint64(body[32:40]) != 0 { + return nil + } + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + player := server.characters[client.id] + if !client.target || server.clients[client.id] != client || !client.ready || client.loading || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id { + server.mutex.Unlock() + return nil + } + index := slices.IndexFunc(player.missions, func(mission acceptedMission) bool { return mission.id == binary.BigEndian.Uint32(body[28:32]) }) + if index < 0 { + server.mutex.Unlock() + return nil + } + updates := make(map[*worldClient][][]byte) + err := server.retireMission_locked(player.missions[index], updates) + server.mutex.Unlock() + if err != nil { + return err + } + updates[client] = append(updates[client], missionRemovalPacket(client.id, binary.BigEndian.Uint32(body[28:32]))) + server.sendCombatUpdates(updates) + return nil +} + +func (server *server) retireMission_locked(mission acceptedMission, updates map[*worldClient][][]byte) error { + // Resolve credentials by instance binding, including copies held by other players. + rows, err := server.db.Query("SELECT item_id FROM mission_keys WHERE mission_id=?", mission.id) + if err != nil { + return err + } + keys := make(map[uint32]bool) + for rows.Next() { + var id uint32 + if err := rows.Scan(&id); err != nil { + rows.Close() + return err + } + keys[id] = true + } + if err := rows.Err(); err != nil { + rows.Close() + return err + } + if err := rows.Close(); err != nil { + return err + } + + // Restore affected draft trades in the candidate, before removing their keys. + inventories := make(map[uint32]playerInventory) + for id, player := range server.characters { + if !player.npc && slices.ContainsFunc(player.inventory.allItems(), func(item ownedItem) bool { return keys[item.ID] }) { + inventories[id] = player.inventory + } + } + hasKey := func(items map[uint32]ownedItem) bool { + for _, item := range items { + if keys[item.ID] { + return true + } + } + return false + } + shops, trades := make(map[*worldClient]bool), make(map[*playerTrade]bool) + for _, client := range server.clients { + if client.shop != nil && hasKey(client.shop.items) { + shops[client] = true + inventories[client.id], _ = restoredTradeInventory(server.characters[client.id].inventory, client.shop.items, tradeSlots(client.shop.items)) + } + if client.trade != nil && !trades[client.trade] && (hasKey(client.trade.items[0]) || hasKey(client.trade.items[1])) { + trades[client.trade] = true + for side, participant := range client.trade.clients { + inventories[participant.id], _ = restoredTradeInventory(server.characters[participant.id].inventory, client.trade.items[side], tradeSlots(client.trade.items[side])) + } + } + } + changes := make(map[*worldClient][][]byte) + for client := range shops { + changes[client] = append(changes[client], shopTradePacket([2]uint32{50000, client.id}, 2, [2]uint32{}, [2]uint32{})) + } + for trade := range trades { + for side, client := range trade.clients { + changes[client] = append(changes[client], shopTradePacket([2]uint32{50000, trade.clients[0].id}, 2, [2]uint32{}, [2]uint32{})) + for offset := range len(trade.items[1-side]) { + changes[client] = append(changes[client], characterActionPacket(trade.clients[1-side].id, [5]uint32{112, 104, 64 + uint32(offset)})) + } + } + } + + // Use the shared inventory transaction for every affected placement and contract. + store, err := server.itemStore_locked(&character{}, playerInventory{}) + if err != nil { + return err + } + store.inventoryPlayers = nil + for id, inventory := range inventories { + client := server.clients[id] + if client != nil { + for _, item := range inventory.Items { + if keys[item.ID] { + changes[client] = append(changes[client], characterActionPacket(id, [5]uint32{112, 104, item.Slot})) + } + } + if client.bank != nil { + for _, item := range inventory.Bank { + if keys[item.ID] { + changes[client] = append(changes[client], characterActionPacket(id, [5]uint32{112, 105, item.Slot})) + } + } + } + for index, handle := range client.backpacks { + for _, item := range inventory.Containers[handle.id] { + if keys[item.ID] { + changes[client] = append(changes[client], characterActionPacket(id, [5]uint32{112, 107, index<<16 | item.Slot})) + } + } + } + for index, item := range client.reclaimItems { + if keys[item] { + changes[client] = append(changes[client], characterActionPacket(id, [5]uint32{112, 106, uint32(index)})) + } + } + } + inventory.Items = slices.DeleteFunc(slices.Clone(inventory.Items), func(item ownedItem) bool { return keys[item.ID] }) + inventory.Bank = slices.DeleteFunc(slices.Clone(inventory.Bank), func(item ownedItem) bool { return keys[item.ID] }) + inventory.Reclaim = slices.DeleteFunc(slices.Clone(inventory.Reclaim), func(item reclaimItem) bool { return keys[item.Item.ID] }) + inventory.Containers = maps.Clone(inventory.Containers) + for bag, items := range inventory.Containers { + inventory.Containers[bag] = slices.DeleteFunc(slices.Clone(items), func(item ownedItem) bool { return keys[item.ID] }) + } + inventories[id] = inventory + store.Players[id] = inventory.references() + store.inventoryPlayers = append(store.inventoryPlayers, id) + } + for id, record := range store.Items { + for _, item := range record.Slots { + if item != nil && keys[*item] { + record.Slots = maps.Clone(record.Slots) + for slot, child := range record.Slots { + if child != nil && keys[*child] { + record.Slots[slot] = nil + } + } + store.Items[id] = record + break + } + } + } + corpses := make(map[uint32]bool) + for id, items := range store.Corpses { + if slices.ContainsFunc(items, func(item ownedItem) bool { return keys[item.ID] }) { + corpses[id] = true + store.Corpses[id] = slices.DeleteFunc(slices.Clone(items), func(item ownedItem) bool { return keys[item.ID] }) + } + } + for id := range keys { + delete(store.Items, id) + } + store.removedMission = &mission + if err := server.writeItemStore_locked(store); err != nil { + return err + } + + // Publish only the committed retirement, preserving unrelated rewards and cash. + for id, inventory := range inventories { + server.characters[id].inventory = inventory + } + for client := range shops { + client.shop = nil + } + for trade := range trades { + for _, client := range trade.clients { + client.trade = nil + } + } + for _, client := range server.clients { + if corpses[client.lootCorpse] { + changes[client] = append(changes[client], lootInventoryPacket(client.id, server.characters[client.lootCorpse], false)) + } + for index, item := range client.reclaimItems { + if keys[item] { + client.reclaimItems[index] = 0 + } + } + } + player := server.characters[mission.owner] + player.missions = slices.DeleteFunc(player.missions, func(other acceptedMission) bool { return other.id == mission.id }) + server.missionExpiry = slices.DeleteFunc(server.missionExpiry, func(other acceptedMission) bool { return other.id == mission.id }) + for client, packets := range changes { + if client.ready && !client.loading { + updates[client] = append(updates[client], packets...) + } + } + return nil +} + +func (server *server) expireMissions_locked(now time.Time, updates map[*worldClient][][]byte) error { + for index := 0; index < len(server.missionExpiry); { + mission := server.missionExpiry[index] + if now.Before(mission.expiresAt) { + index++ + continue + } + if err := server.retireMission_locked(mission, updates); err != nil { + return err + } + if client := server.clients[mission.owner]; client != nil && client.ready && !client.loading { + updates[client] = append(updates[client], missionExpiryPacket(mission.owner, mission.id)) + } + } + return nil +} + +func (server *server) advanceMissions(now time.Time) { + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + updates := make(map[*worldClient][][]byte) + err := server.expireMissions_locked(now, updates) + server.mutex.Unlock() + if err != nil { + log.Printf("Expiring missions: %v", err) + } + server.sendCombatUpdates(updates) +} diff --git a/server/mission_retirement_test.go b/server/mission_retirement_test.go @@ -0,0 +1,546 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "reflect" + "slices" + "sync" + "testing" + "time" +) + +func newAcceptedMissionWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, output := newMissionOfferWorld(t) + client := world.clients[1] + if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil { + t.Fatal(err) + } + if err := world.handleMissionAcceptance(client, missionAcceptanceRequest(*client.missionOffer)); err != nil { + t.Fatal(err) + } + output.packets = nil + return world, output +} + +func TestMissionRemovalNativeDispatchAndNextAssignment(t *testing.T) { + newAcceptedMissionWorld(t) + world := newTestInventoryServer(t) + connection := connectZoningClient(t, world, true) + defer connection.Close() + + if _, err := connection.Write(targetPacket(missionRemovalPacket(1, 2))); err != nil { + t.Fatal(err) + } + key, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + journal, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + if _, err := connection.Write(targetPacket(n3Packet(0x5c436609, 50000, 1, missionOffersRequest()[16:]))); err != nil { + t.Fatal(err) + } + if _, err := readPacket(connection); err != nil { + t.Fatal(err) + } + offer, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + selection := slices.Clone(offer[29:51]) + selection[0], selection[21] = 2, 0 + if _, err := connection.Write(targetPacket(n3Packet(0x291f361b, 50000, 1, selection))); err != nil { + t.Fatal(err) + } + for range 2 { + if _, err := readPacket(connection); err != nil { + t.Fatal(err) + } + } + next := newTestInventoryServer(t).characters[1] + + if !bytes.Equal(key, targetPacket(characterActionPacket(1, [5]uint32{112, 104, 65}))[:len(key)]) || !bytes.Equal(journal, targetPacket(missionRemovalPacket(1, 2))[:len(journal)]) || + len(cold.characters[1].missions) != 0 || len(cold.missionExpiry) != 0 || len(cold.characters[1].inventory.Items) != 1 || + cold.characters[1].inventory.Credits != 4 || cold.characters[1].experience != 0 || len(captureMissionReplay(t, cold, 1)) != 0 { + t.Fatalf("abandonment state: key=%x journal=%x missions=%d expiry=%d inventory=%+v XP=%d", key, journal, len(cold.characters[1].missions), len(cold.missionExpiry), cold.characters[1].inventory, cold.characters[1].experience) + } + if len(next.missions) != 1 || next.missions[0].id != 3 || len(next.inventory.Items) != 2 || next.inventory.Items[1].ID != 3 || next.inventory.Credits != 3 { + t.Fatal("retired mission blocked the next assignment or reused its identity") + } +} + +func TestMissionRemovalRejectsMalformedForeignAndStaleRequests(t *testing.T) { + for _, scenario := range []string{"short", "long", "version", "action", "quest type", "quest id", "subject type", "subject id", "secondary type", "secondary id", "loading", "not ready", "stale", "legacy"} { + t.Run(scenario, func(t *testing.T) { + world, output := newAcceptedMissionWorld(t) + client, player := world.clients[1], world.characters[1] + request := missionRemovalPacket(1, 2)[20:] + switch scenario { + case "short": + request = request[:39] + case "long": + request = append(request, 0) + case "version": + binary.BigEndian.PutUint32(request[16:20], 2) + case "action": + binary.BigEndian.PutUint32(request[20:24], 1) + case "quest type": + binary.BigEndian.PutUint32(request[24:28], 50000) + case "quest id": + binary.BigEndian.PutUint32(request[28:32], 3) + case "subject type": + binary.BigEndian.PutUint32(request[4:8], 56003) + case "subject id": + binary.BigEndian.PutUint32(request[8:12], 2) + case "secondary type": + binary.BigEndian.PutUint32(request[32:36], 50000) + case "secondary id": + binary.BigEndian.PutUint32(request[36:40], 1) + case "loading": + client.loading = true + case "not ready": + client.ready = false + case "stale": + world.clients[1] = &worldClient{id: 1} + case "legacy": + client.target = false + } + before := player.inventory + + err := world.handleMissionRemoval(client, request) + cold := newTestInventoryServer(t).characters[1] + + if err != nil || len(output.packets) != 0 || len(player.missions) != 1 || len(world.missionExpiry) != 1 || len(cold.missions) != 1 || + !reflect.DeepEqual(before, player.inventory) || !reflect.DeepEqual(before, cold.inventory) { + t.Fatal("invalid removal changed the mission or its key", err) + } + }) + } +} + +func TestMissionRemovalFailureRollsBackThenRetries(t *testing.T) { + for _, table := range []string{"items", "item_locations", "mission_keys", "missions"} { + for _, fault := range []string{"ABORT", "IGNORE", "commit"} { + t.Run(table+"/"+fault, func(t *testing.T) { + world, output := newAcceptedMissionWorld(t) + client, player := world.clients[1], world.characters[1] + before := player.inventory + statement := fmt.Sprintf("CREATE TRIGGER fail_retire BEFORE DELETE ON %s BEGIN SELECT RAISE(%s, 'retirement'); END", table, fault) + if fault == "IGNORE" { + statement = fmt.Sprintf("CREATE TRIGGER fail_retire BEFORE DELETE ON %s BEGIN SELECT RAISE(IGNORE); END", table) + } + if fault == "commit" { + statement = fmt.Sprintf("CREATE TABLE pending_retire (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_retire AFTER DELETE ON %s BEGIN INSERT INTO pending_retire VALUES (999999); END", table) + } + if _, err := world.db.Exec(statement); err != nil { + t.Fatal(err) + } + + err := world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + cold := newTestInventoryServer(t).characters[1] + + if err == nil || len(output.packets) != 0 || len(player.missions) != 1 || len(world.missionExpiry) != 1 || len(cold.missions) != 1 || + !reflect.DeepEqual(before, player.inventory) || !reflect.DeepEqual(before, cold.inventory) || world.nextItem != 2 { + t.Fatal("failed retirement published state or lost its contract/key", err) + } + if _, err := world.db.Exec("DROP TRIGGER fail_retire"); err != nil { + t.Fatal(err) + } + + err = world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + duplicate := world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + cold = newTestInventoryServer(t).characters[1] + + var bindings int + if scan := world.db.QueryRow("SELECT count(*) FROM mission_keys").Scan(&bindings); scan != nil { + t.Fatal(scan) + } + if err != nil || duplicate != nil || len(output.packets) != 2 || len(player.missions) != 0 || len(cold.missions) != 0 || + len(world.missionExpiry) != 0 || len(cold.inventory.Items) != 1 || bindings != 0 || cold.inventory.Credits != 4 || cold.experience != 0 { + t.Fatal("retry did not retire exactly one contract/key without rewards", err, duplicate) + } + }) + } + } +} + +func TestMissionExpiryDeadlineRetryAndColdStartup(t *testing.T) { + for _, scenario := range []string{"online", "offline", "startup", "retry"} { + t.Run(scenario, func(t *testing.T) { + world, output := newAcceptedMissionWorld(t) + deadline := world.characters[1].missions[0].expiresAt + var writesBefore, writesAfter int + if err := world.db.QueryRow("SELECT total_changes()").Scan(&writesBefore); err != nil { + t.Fatal(err) + } + if scenario == "offline" { + delete(world.clients, 1) + } + if scenario == "retry" { + if _, err := world.db.Exec("CREATE TRIGGER fail_expiry BEFORE DELETE ON missions BEGIN SELECT RAISE(ABORT, 'expiry'); END"); err != nil { + t.Fatal(err) + } + } + + for range 10 { + world.advanceMissions(deadline.Add(-time.Nanosecond)) + } + if err := world.db.QueryRow("SELECT total_changes()").Scan(&writesAfter); err != nil { + t.Fatal(err) + } + + if len(world.characters[1].missions) != 1 || len(output.packets) != 0 || writesAfter != writesBefore { + t.Fatal("pending mission expired early or caused database churn") + } + + if scenario == "startup" { + if _, err := world.db.Exec("UPDATE missions SET expires_at=?", time.Now().Add(-time.Second).UTC().Format(time.RFC3339Nano)); err != nil { + t.Fatal(err) + } + world = newTestInventoryServer(t) + } else { + world.advanceMissions(deadline) + } + if scenario == "retry" { + if len(world.characters[1].missions) != 1 || len(output.packets) != 0 || len(world.missionExpiry) != 1 { + t.Fatal("failed expiry published state or consumed its pending deadline") + } + if _, err := world.db.Exec("DROP TRIGGER fail_expiry"); err != nil { + t.Fatal(err) + } + world.advanceMissions(deadline.Add(time.Second)) + } + world.advanceMissions(deadline.Add(time.Hour)) + cold := newTestInventoryServer(t).characters[1] + + if len(world.characters[1].missions) != 0 || len(world.missionExpiry) != 0 || len(cold.missions) != 0 || len(cold.inventory.Items) != 1 || cold.inventory.Credits != 4 || cold.experience != 0 { + t.Fatal("deadline retirement was not durable or granted completion rewards") + } + want := 2 + if scenario == "offline" || scenario == "startup" { + want = 0 + } + if len(output.packets) != want { + t.Fatal("expiry sent missing, repeated or offline notifications", len(output.packets)) + } + if want == 2 && (binary.BigEndian.Uint32(output.packets[1][16:20]) != 0x5f2e1b19 || + !bytes.Equal(output.packets[1][29:45], []byte{0, 0, 0, 1, 0, 0, 218, 195, 0, 0, 0, 2, 0, 0, 0, 1})) { + t.Fatal("expiry omitted the native QuestEvent1 identity/reason") + } + }) + } +} + +func TestMissionRemovalConcurrentExpiryAndDuplicateRequests(t *testing.T) { + world, output := newAcceptedMissionWorld(t) + client := world.clients[1] + deadline := world.characters[1].missions[0].expiresAt + var pending sync.WaitGroup + failures := make(chan error, 2) + + for range 2 { + pending.Add(1) + go func() { + defer pending.Done() + failures <- world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + }() + } + pending.Add(1) + go func() { defer pending.Done(); world.advanceMissions(deadline) }() + pending.Wait() + close(failures) + cold := newTestInventoryServer(t).characters[1] + + for err := range failures { + if err != nil { + t.Fatal(err) + } + } + if len(output.packets) != 2 || len(cold.missions) != 0 || len(cold.inventory.Items) != 1 || cold.inventory.Credits != 4 || world.nextItem != 2 { + t.Fatal("concurrent retirement duplicated output, lost unrelated inventory or paid rewards") + } +} + +func TestMissionRemovalBoundKeysAcrossLocationsPreservesUnrelatedItems(t *testing.T) { + for _, location := range []string{"bank", "backpack", "reclaim", "offline holder", "unassigned", "unassigned backpack", "corpse"} { + t.Run(location, func(t *testing.T) { + world, output := newAcceptedMissionWorld(t) + player, client := world.characters[1], world.clients[1] + key := player.inventory.Items[1] + inventory := player.inventory + inventory.LastID = 5 + inventory.Items = append(slices.Clone(inventory.Items[:1]), + ownedItem{ID: 3, Type: 51053, Template: 28577, Quality: 1, Slot: 66, Count: 1}, + ownedItem{ID: 4, Type: 51005, Template: 40822, Quality: 1, Slot: 67, Count: 1}) + switch location { + case "bank": + key.Slot = 7 + inventory.Bank = []ownedItem{key} + client.bank = &bankSession{} + case "backpack": + key.Slot = 3 + inventory.Items = append(inventory.Items, ownedItem{ID: 5, Type: 51017, Template: 99228, Quality: 1, Slot: 68, Count: 1}) + inventory.Containers = map[uint32][]ownedItem{5: {key}} + client.backpacks = map[uint32]backpackHandle{2: {id: 5, open: true}} + case "reclaim": + inventory.Reclaim = []reclaimItem{{Item: key, AvailableAt: time.Now().UTC().Add(time.Hour)}} + client.reclaimItems = []uint32{0, 2, 0, 4} + case "offline holder": + world.nextCharacter = 1 + peer := world.newCharacter() + if err := world.saveUser_locked(peer); err != nil { + t.Fatal(err) + } + key.Slot = 64 + peer.inventory = playerInventory{LastID: 5, Items: []ownedItem{key}} + case "corpse": + npc := world.characters[1000000] + npc.health, npc.corpse = 0, &npcCorpse{items: []ownedItem{key}, expiresAt: time.Now().Add(time.Hour)} + client.lootCorpse = npc.id + } + if location == "unassigned" || location == "unassigned backpack" { + store, err := world.itemStore_locked(player, inventory) + if err != nil { + t.Fatal(err) + } + store.Items[2] = recordItem(key, nil) + if location == "unassigned backpack" { + store.Items[5] = itemRecord{Type: 51017, Template: 99228, Quality: 1, Count: 1, Slots: map[string]*uint32{"slot_4": &key.ID}} + } + if err := world.writeItemStore_locked(store); err != nil { + t.Fatal(err) + } + player.inventory = inventory + } else if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + before := newTestInventoryServer(t) + if _, err := world.db.Exec("CREATE TRIGGER fail_placement_retire BEFORE DELETE ON missions BEGIN SELECT RAISE(ABORT, 'retirement'); END"); err != nil { + t.Fatal(err) + } + output.packets = nil + + err := world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + + if err == nil || len(output.packets) != 0 || len(player.missions) != 1 || !reflect.DeepEqual(world.items, before.items) || !reflect.DeepEqual(player.inventory, before.characters[1].inventory) { + t.Fatal("failed retirement mutated live placement/container aliases") + } + if location == "corpse" && !slices.Equal(world.characters[1000000].corpse.items, before.characters[1000000].corpse.items) || + location == "offline holder" && !reflect.DeepEqual(world.characters[2].inventory, before.characters[2].inventory) { + t.Fatal("failed retirement changed an offline holder or corpse") + } + if _, err := world.db.Exec("DROP TRIGGER fail_placement_retire"); err != nil { + t.Fatal(err) + } + + err = world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + cold := newTestInventoryServer(t) + + if err != nil || len(cold.characters[1].missions) != 0 || len(world.missionExpiry) != 0 || len(cold.characters[1].inventory.Reclaim) != 0 || + len(cold.characters[1].inventory.Bank) != 0 || cold.characters[1].inventory.Credits != 4 || cold.characters[1].experience != 0 { + t.Fatal("retirement lost accounting or left a placed credential", err) + } + for _, state := range []*server{world, cold} { + if _, exists := state.items[2]; exists || state.items[3].Template != 28577 || state.items[4].Template != 40822 || + slices.ContainsFunc(state.characters[1].inventory.allItems(), func(item ownedItem) bool { return item.ID == 2 }) { + t.Fatal("retirement retained its credential or deleted unrelated keys/objective items") + } + if location == "offline holder" && len(state.characters[2].inventory.Items) != 0 { + t.Fatal("offline holder retained the retired credential") + } + } + if location == "reclaim" && !slices.Equal(client.reclaimItems, []uint32{0, 0, 0, 4}) { + t.Fatal("retirement changed stable reclaim indices") + } + var removal []byte + switch location { + case "bank": + removal = characterActionPacket(1, [5]uint32{112, 105, 7}) + case "backpack": + removal = characterActionPacket(1, [5]uint32{112, 107, 2<<16 | 3}) + case "reclaim": + removal = characterActionPacket(1, [5]uint32{112, 106, 1}) + case "corpse": + removal = lootInventoryPacket(1, world.characters[1000000], false) + if len(world.characters[1000000].corpse.items) != 0 || len(cold.characters[1000000].corpse.items) != 0 { + t.Fatal("corpse retained the retired key") + } + } + if removal != nil && (len(output.packets) != 2 || !bytes.Equal(output.packets[0], targetPacket(removal))) { + t.Fatal("open native placement retained a ghost key") + } + }) + } +} + +func TestMissionRemovalCancelsAffectedTradesOnlyAfterCommit(t *testing.T) { + for _, kind := range []string{"shop", "player"} { + t.Run(kind, func(t *testing.T) { + world, output := newAcceptedMissionWorld(t) + player, client := world.characters[1], world.clients[1] + key := player.inventory.Items[1] + // Leave a hole: native Cancel restores the offered key into slot64 before removal. + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + inventory.Items[0].Slot = 70 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if kind == "shop" { + client.shop = &shopTrade{items: map[uint32]ownedItem{0: key}, purchases: map[uint32]uint16{0: 1}} + } else { + world.nextCharacter = 1 + peer := world.newCharacter() + if err := world.saveUser_locked(peer); err != nil { + t.Fatal(err) + } + other := &worldClient{id: 2, conn: &combatTestConn{}, target: true, ready: true} + world.clients[2] = other + trade := &playerTrade{clients: [2]*worldClient{client, other}, items: [2]map[uint32]ownedItem{{0: key}, {}}, accepted: [2]bool{true, false}} + client.trade, other.trade = trade, trade + } + if _, err := world.db.Exec("CREATE TRIGGER fail_trade_retire BEFORE DELETE ON missions BEGIN SELECT RAISE(ABORT, 'retirement'); END"); err != nil { + t.Fatal(err) + } + output.packets = nil + + err := world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + + if err == nil || len(output.packets) != 0 || !reflect.DeepEqual(player.inventory, inventory) || kind == "shop" && client.shop == nil || kind == "player" && client.trade == nil { + t.Fatal("failed retirement restored/published inventory or consumed its trade") + } + if _, err := world.db.Exec("DROP TRIGGER fail_trade_retire"); err != nil { + t.Fatal(err) + } + + err = world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + for _, action := range []uint32{1, 2} { + if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, action, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + } + cold := newTestInventoryServer(t) + + if err != nil || client.shop != nil || client.trade != nil || len(output.packets) != 3 || len(cold.characters[1].inventory.Items) != 1 || + cold.characters[1].inventory.Items[0].ID != 1 || cold.characters[1].inventory.Items[0].Slot != 70 || cold.characters[1].inventory.Credits != 4 || + !bytes.Equal(output.packets[1], targetPacket(characterActionPacket(1, [5]uint32{112, 104, 64}))) { + t.Fatal("retirement failed to cancel/restage a trade or a late packet resurrected/sold its key", err) + } + if kind == "player" && (world.clients[2].trade != nil || len(cold.characters[2].inventory.Items) != 0) { + t.Fatal("peer retained the cancelled trade or received the retired key") + } + }) + } +} + +func TestMissionExpiryIndependentOwnersCopiesAndPartialFailure(t *testing.T) { + world, output := newAcceptedMissionWorld(t) + world.nextCharacter = 1 + peer := world.newCharacter() + peer.playfield, peer.position, peer.appearance = 3000, [3]float32{100, 115.75, 145}, 277 + if err := world.saveUser_locked(peer); err != nil { + t.Fatal(err) + } + inventory := peer.inventory + inventory.Credits = 5 + if err := world.saveInventory_locked(peer, inventory); err != nil { + t.Fatal(err) + } + otherOutput := &combatTestConn{} + other := &worldClient{id: 2, conn: otherOutput, target: true, ready: true} + world.clients[2] = other + request := missionOffersRequest() + binary.BigEndian.PutUint32(request[8:12], 2) + if err := world.handleMissionOffers(other, request); err != nil { + t.Fatal(err) + } + request = missionAcceptanceRequest(*other.missionOffer) + binary.BigEndian.PutUint32(request[8:12], 2) + if err := world.handleMissionAcceptance(other, request); err != nil { + t.Fatal(err) + } + inventory = peer.inventory + inventory.LastID = 4 + inventory.Bank = []ownedItem{{ID: 4, Type: 51053, Template: 28577, Quality: 1, Slot: 8, Count: 1}} + if err := world.saveInventory_locked(peer, inventory); err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec("INSERT INTO mission_keys VALUES (4, 2)"); err != nil { + t.Fatal(err) + } + other.bank = &bankSession{} + output.packets, otherOutput.packets = nil, nil + + err := world.handleMissionRemoval(other, missionRemovalPacket(2, 2)[20:]) + deadline := peer.missions[0].expiresAt + world.advanceMissions(deadline.Add(-48 * time.Hour)) + + if err != nil || len(output.packets) != 0 || len(otherOutput.packets) != 0 || len(world.characters[1].missions) != 1 || len(peer.missions) != 1 { + t.Fatal("another owner retired a foreign contract or a mission expired early", err) + } + if _, err := world.db.Exec("CREATE TRIGGER fail_second_expiry BEFORE DELETE ON missions WHEN OLD.id=3 BEGIN SELECT RAISE(ABORT, 'second expiry'); END"); err != nil { + t.Fatal(err) + } + + world.advanceMissions(deadline) + cold := newTestInventoryServer(t) + + if len(output.packets) != 2 || len(otherOutput.packets) != 1 || len(world.characters[1].missions) != 0 || len(peer.missions) != 1 || + len(world.missionExpiry) != 1 || len(cold.characters[1].missions) != 0 || len(cold.characters[2].missions) != 1 || + len(cold.characters[2].inventory.Bank) != 0 || len(cold.characters[2].inventory.Items) != 1 || cold.characters[2].inventory.Items[0].ID != 3 || + !bytes.Equal(otherOutput.packets[0][16:], targetPacket(characterActionPacket(2, [5]uint32{112, 105, 8}))[16:]) { + t.Fatal("one failed expiry hid the committed retirement or destroyed another owner's contract/key") + } + if _, err := world.db.Exec("DROP TRIGGER fail_second_expiry"); err != nil { + t.Fatal(err) + } + + world.advanceMissions(deadline) + cold = newTestInventoryServer(t) + + if len(world.missionExpiry) != 0 || len(otherOutput.packets) != 3 || len(cold.characters[2].missions) != 0 || len(cold.characters[2].inventory.Items) != 0 || + cold.characters[1].inventory.Credits != 4 || cold.characters[2].inventory.Credits != 4 || len(cold.items) != 1 { + t.Fatal("retry did not retire only the remaining mission and its key") + } +} + +func TestMissionRemovalOutputFailureRetainsDurableRetirement(t *testing.T) { + world, output := newAcceptedMissionWorld(t) + client := world.clients[1] + client.writeWake, client.writeClosed = make(chan struct{}, 1), true + + err := world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + retry := world.handleMissionRemoval(client, missionRemovalPacket(1, 2)[20:]) + cold := newTestInventoryServer(t) + journal := captureMissionReplay(t, cold, 1) + + if err != nil || retry != nil || len(output.packets) != 0 || len(journal) != 0 || len(cold.characters[1].missions) != 0 || + len(cold.characters[1].inventory.Items) != 1 || cold.characters[1].inventory.Credits != 4 || cold.nextItem != 2 { + t.Fatal("output failure restored/duplicated a committed retirement or paid rewards", err, retry) + } +} + +func TestMissionRemovalDeadOwnerCanAbandonAwayFromTerminal(t *testing.T) { + world, output := newAcceptedMissionWorld(t) + player := world.characters[1] + player.health, player.playfield, player.position = 0, 800, [3]float32{500, 0, 500} + + world.advanceMissions(player.missions[0].expiresAt.Add(-time.Hour)) + + if len(player.missions) != 1 || len(output.packets) != 0 { + t.Fatal("death or leaving the mission zone retired an unexpired contract") + } + + err := world.handleMissionRemoval(world.clients[1], missionRemovalPacket(1, 2)[20:]) + cold := newTestInventoryServer(t).characters[1] + + if err != nil || len(output.packets) != 2 || len(cold.missions) != 0 || len(cold.inventory.Items) != 1 || cold.inventory.Credits != 4 || cold.experience != 0 { + t.Fatal("journal abandonment incorrectly required a living owner near the terminal", err) + } +} diff --git a/server/missions.go b/server/missions.go @@ -54,6 +54,7 @@ func (server *server) loadMissions() error { } player := server.characters[mission.owner] player.missions = append(player.missions, mission) + server.missionExpiry = append(server.missionExpiry, mission) } return rows.Err() } @@ -116,6 +117,7 @@ func (server *server) handleMissionAcceptance(client *worldClient, body []byte) } player.inventory = inventory player.missions = append(player.missions, mission) + server.missionExpiry = append(server.missionExpiry, mission) client.missionOffer = nil // Add the native template proxy only after the key and journal are durable. diff --git a/server/roaming.go b/server/roaming.go @@ -20,6 +20,7 @@ func (server *server) roamNPCs() { ticker := time.NewTicker(250 * time.Millisecond) defer ticker.Stop() for now := range ticker.C { + server.advanceMissions(now) server.advanceCorpseExpiry(now) server.advanceNPCRespawns(now) server.advanceNPCs(now) diff --git a/server/state.go b/server/state.go @@ -132,6 +132,7 @@ type server struct { roamingNPCs map[uint32][]*character npcRespawns []npcRespawn corpseExpiry []*character + missionExpiry []acceptedMission clients map[uint32]*worldClient fighting map[uint32]*character combatRoll func(uint32) uint32 diff --git a/server/users.go b/server/users.go @@ -159,6 +159,9 @@ func (server *server) loadUsers() error { if err := server.loadMissions(); err != nil { return err } + if err := server.expireMissions_locked(time.Now(), nil); err != nil { + return err + } // No cast survives process startup; restore its reserved points exactly once. for _, player := range server.characters { if !player.npc && player.nanoReserved != 0 {