commit 046f2b5b9e3cd9d06fb572ee532c45bc6f322dfa
parent ebff29d4cb0c1cbb928881efddfe4cc088ef7c78
Author: anon <anon@example.com>
Date: Tue, 27 Oct 2026 06:12:49 +0000
Persist accepted starter missions and native journals
Diffstat:
17 files changed, 649 insertions(+), 20 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -1373,16 +1373,29 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
Cold server/client reconnect retains the fee and an empty accepted journal.
Narrative, reward amounts and duration are provisional; acceptance is separate.
See [mission offers](docs/mission-offers.md).
-- [ ] [P1] Accept that mission. Check: its journal entry and assigned destination
+- [x] Accept that mission. Check: its journal entry and assigned destination
survive reconnect.
- Native CreateQuest0x291f361b/version2 carries difficulty, six dimensions,
- offer seed, originator/booth and selection index. Validate a currently offered
- contract owned by this session before committing acceptance and key assignment.
+ Native CreateQuest0x291f361b/version2 validates the session's exact offered
+ contract. Contract, exterior entrance/position and key28577 ownership commit
+ atomically before the native journal reply. The original one-training-mission
+ limit prevents duplicate fees/keys. Go tests cover forged/stale selections,
+ concurrent/repeated acceptance, ignored/failed writes and commits, lost output,
+ changed YAML, profile edits/checkpoints and owner-only cold replay. GPU WASM
+ verifies the journal, key/details and coordinate upload after a cold restart.
+ The saved exterior is not a private interior assignment; that remains below.
+ See [mission acceptance](docs/mission-acceptance.md).
- [ ] [P1] Enter and leave one fixed mission interior. Check: the assigned door
selects the right instance and returns the player to the right entrance.
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.
+- [ ] [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.
+ Current keys show the base "Mission Key to" name; the server persists their
+ contract association, but native destination metadata and usable entry remain
+ unimplemented. Cover held, banked, traded, deleted and reclaimed keys; possession
+ of an unrelated template28577 must never admit a player to another mission.
- [ ] [P1] Complete one mission objective. Check: a chosen target or object completes
the mission once, with the expected reward.
Commit completion with XP, credits and any item reward atomically through the
@@ -1395,6 +1408,10 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
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.
- [ ] [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.
diff --git a/docs/mission-acceptance.md b/docs/mission-acceptance.md
@@ -0,0 +1,97 @@
+# Accepted starter missions
+
+CreateQuest0x291f361b/version2 now accepts the currently offered starter
+contract. Acceptance commits an immutable contract, its first key28577 and key
+ownership in one SQLite transaction before sending native success. It grants no
+completion rewards and does not yet allocate or enter a private interior.
+
+## Contract and ownership
+
+The session retains its last successfully generated offer after the generation
+fee commits. Acceptance must match its seed, difficulty, all six dimensions,
+originator, booth identity and selection index0. A replaced session cannot use
+that offer. Regeneration replaces it; an empty generation reply clears it.
+Database failure preserves it for a retry. Significant admission conditions,
+including current position, life, readiness, free slots and template Use gates,
+are checked again before accepting.
+
+The original shipped `OnReceiveMission.txt` says only one training mission is
+available at a time. The supported starter contract observes that limit. An
+already accepted mission prevents another generation fee or duplicate key.
+Ordinary city/team mission capacity remains unimplemented with their content.
+
+The `missions` table stores scalar contract values, offer parameters, owner,
+exterior entrance/position and expiry. Neither acceptance nor reconnect consults
+the current mission YAML for those values. The durable mission identity uses
+the newly allocated first key's numeric instance ID in the distinct56003 quest
+identity namespace. `mission_keys` binds actual item instances to missions;
+template28577 alone is not an admission credential. Its first key is original
+type51053/QL1. Deleting a key removes its binding, without deleting the contract.
+Copying keys and their usable native destination metadata remain open.
+
+The shared inventory transaction persists item allocation, placement, contract
+and key binding before publishing live state. Ignored inserts are detected with
+RETURNING. A failed write or commit creates no key or journal and consumes no
+offer. Output failure after commit retains the accepted state for reconnect.
+Normal inventory saves and periodic checkpoints leave contracts intact. Player
+replacement during zoning/control edits preserves the in-memory journal.
+
+## Native journal
+
+Original14.9.1 `kkr.dll`, SHA256
+`241b2e665dcd127399b7686cddda8a5b0876d9cde9b3af7a73940dd0b86ecaa7`,
+registers QuestFullUpdateIIR through factory0x36011de0/constructor0x360c6ca0.
+Its native reader0x360c6d00 and writer0x360c6dd0 carry a DWORD version1,
+DWORD category, quest identity and complete Quest14 record. Evidence IDs are
+`ev_83bcb6dcd109658d780db58dc377b741d06ab63bf5b220620a4ccf6eacb9d564`
+and `ev_011c904a2d9c6efbbc66e5e311c5b3b206767a6b945c6a71d9b1894854d19752`.
+The version constant at0x361c91f0 is1
+(`ev_56ff7855188a3c4e8bd03224001f72443cae80ed290608d704035f09f6485d73`).
+The message-name hash candidate0x465a4061 is corroborated by actual native
+delivery, rather than inferred from its name alone.
+
+The native Apply entry0x360c6e30 lacks a Ghidra function boundary. Its decoded
+instructions and maintained `sub_360C6E30` call0x3606bc60 with the parsed quest
+and category. That consumer distinguishes category2 for created missions from
+assigned missions, appends assigned identities to the list returned by
+N3Msg_GetQuestList(1), and reports "You got a new mission."
+Consumer evidence is
+`ev_c83fcafaffa61147fcee8ef9bd3bcfa716efd76687526fd2deb2bbec974be893`;
+list evidence is
+`ev_7f5db6f6719a005198a0fb2e0344ef16b82d3514a93becd65bf0190e0d6ed8d4`.
+The server uses category1 and includes the owner in Quest14's owners list.
+Browsing and journal replay share the same serializer, with remaining time
+derived from the saved expiry. FullCharacter restores inventory before the
+owner-only journal replay; journals are never broadcast to nearby players.
+Complete REA provenance is retained in `local/mission-acceptance/kkr-evidence.json`.
+
+## Verification and remaining work
+
+The focused Go run passed22 roots/149 test results. Coverage includes native
+socket generation/acceptance, all altered offer fields, stale sessions, admission
+changes, repeated/concurrent acceptance, owner-only cold replay and failure
+injection at item, placement, contract and key-binding writes. Each write has
+abort, ignored-insert and deferred-commit cases. Lost output after commit
+retains exactly one contract/key. Profile edits, inventory saving, checkpoints
+and changed YAML do not replace the accepted values.
+The signed-parameter replay test also retains mixed negative/positive dimensions
+at difficulty11. Concurrent generation and acceptance passed the race detector;
+the full gamedata package passed.
+
+Headed Chromium on the GPU accepted the actual backyard3000 offer and
+displayed the native success text, Assumed Missions icon, description and key
+inventory/info. A cold server restart and client reconnect without fixture edits
+retained the journal, same key instance/binding, level1, XP0 and four credits.
+Uploading coordinates from the cold journal's native radial menu placed the
+white map marker at the saved exterior entrance. The fixture started with five
+controlled credits; this is not an earned-income proof. No adapter crash or page
+exception occurred. Startup still logged unattributed HTTP404s. Captures,
+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).
diff --git a/docs/mission-offers.md b/docs/mission-offers.md
@@ -3,7 +3,8 @@
The backyard3000 mission booth now returns one browsable contract through the
original 14.9.1 selection window. Opening, generating and accepting are separate
operations. Generation charges credits but does not grant a mission, key, item,
-XP or reward credits. CreateQuest acceptance is not implemented yet.
+XP or reward credits. [CreateQuest acceptance](mission-acceptance.md) now persists
+the selected contract and its first key separately from generation.
## Content and scope
@@ -66,8 +67,9 @@ The chosen fee is a reconstruction consistent with that precheck.
key0x291f361b/version2 with payload
`0206000000000000c70a4af5050000dac1c0000bb800`: difficulty6, neutral dimensions,
offer seed0xc70a4af5, origin5, booth56001/3221228472 and selection index0.
-No handler currently commits that request. The native window closes but its
-journal stays empty; this is evidence for the next integration, not acceptance.
+That initial capture preceded the acceptance handler. Its window closed with an
+empty journal. The current handler and verified journal/key replay are covered
+in [mission acceptance](mission-acceptance.md).
## Verification
@@ -101,9 +103,8 @@ retained in `local/mission-offers/`.
## Next integration
-Acceptance must authenticate an offered contract and persist its immutable
-values, journal, key and destination together before publication. The current
-serializer retains no accepted or pending mission state. Private instances need
+Acceptance now authenticates the session offer and persists its immutable values,
+journal, first key and exterior destination before publication. Private instances need
explicit isolation across all world consumers before admitting players. An
arbitrary existing Blue Book must not satisfy a new contract. Completion needs
verified objective/token rules and atomic rewards through shared progression
diff --git a/docs/mission-terminals.md b/docs/mission-terminals.md
@@ -122,9 +122,9 @@ team membership alone does not replace a key.
## Remaining integration
-Offers must remain distinct from accepted contracts. Persist acceptance,
-contract values and destination assignment together before sending success;
-replay the journal only to the owner. Private interiors require an explicit
+Offers remain distinct from [accepted contracts](mission-acceptance.md), whose
+values, exterior destination and first key now commit together before success;
+journal replay reaches only the owner. Private interiors require an explicit
world instance distinct from the client asset playfield. Current visibility,
combat, nanos, loot, inspection, trade, chat and broadcasts use playfield alone;
sharing a fixed template would leak actors across missions.
diff --git a/server/control.go b/server/control.go
@@ -314,6 +314,7 @@ func (server *server) prepareUser_locked(character, updated *character) {
updated.activeNanos = character.activeNanos
updated.team = character.team
updated.buddies = character.buddies
+ updated.missions = character.missions
// Reconnection cancels a pending cast; preserve its refund unless nano was edited.
if updated.nano == character.nano {
updated.nano = min(character.maximumNano(), character.nano+character.nanoReserved)
diff --git a/server/gamedata/mission_booths_test.go b/server/gamedata/mission_booths_test.go
@@ -87,7 +87,7 @@ func TestStarterMissionTemplateReferencesOriginalAssets(t *testing.T) {
item := ItemTemplates[definition.ObjectiveItem]
- if definition.Playfield != booth.Playfield || definition.Playfield != 3000 ||
+ if definition.Playfield != booth.Playfield || definition.Playfield != 3000 || definition.Entrance != 3221228472 ||
definition.Position != [3]float32{89.30216217041016, 115.14443969726562, 151.16087341308594} ||
item == nil || item.ID != 40822 || item.Quality == nil || *item.Quality != 1 ||
item.PayloadSHA256 != "645b946ec12830a3695e1c27659dc37676dbc2b884cb1f19e4fda1692e7066fe" {
diff --git a/server/gamedata/missions.yaml b/server/gamedata/missions.yaml
@@ -8,6 +8,7 @@
Locate the Blue Book of Secrets inside the Surveillance Office and recover it.
The entrance is in Omni-1 Entertainment Backyard 1, near the mission booth.
playfield: 3000
+ entrance: 3221228472
position: [89.30216217041016, 115.14443969726562, 151.16087341308594]
objective_item: 40822
credits: 20
diff --git a/server/gamedata/types.go b/server/gamedata/types.go
@@ -18,6 +18,7 @@ type MissionBooth struct {
type MissionTemplate struct {
Description string `yaml:"description"`
Playfield uint32 `yaml:"playfield"`
+ Entrance uint32 `yaml:"entrance"`
Position [3]float32 `yaml:"position"`
ObjectiveItem uint32 `yaml:"objective_item"`
Credits uint32 `yaml:"credits"`
diff --git a/server/item_database.go b/server/item_database.go
@@ -177,6 +177,11 @@ func (server *server) persistItems_locked(store itemStore) error {
return err
}
}
+ if store.mission != nil {
+ if err := insertMission(tx, store.mission); err != nil {
+ return 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
@@ -52,6 +52,7 @@ type itemStore struct {
edited *character
vitalUpdate *playerVitalUpdate
skillLock *skillLockUpdate
+ mission *acceptedMission
inventoryPlayers []uint32
checkpointAt time.Time
flush bool
diff --git a/server/main.go b/server/main.go
@@ -399,6 +399,9 @@ func (server *server) serveWorldClient(client *worldClient) error {
updates = append(updates, server.chatServerPacket(conn))
}
updates = append(updates, fullCharacterPacket(character))
+ for _, mission := range character.missions {
+ updates = append(updates, missionJournalPacket(mission, time.Now()))
+ }
updates = append(updates, activeNanoPackets(character, time.Now())...)
if len(character.activeNanos) != 0 {
// FullCharacter recomputes maxima before the later ability replay.
@@ -492,6 +495,10 @@ func (server *server) serveWorldClient(client *worldClient) error {
decodeInventory1491(body)
}
switch binary.BigEndian.Uint32(body[0:4]) {
+ case 0x291f361b:
+ if err := server.handleMissionAcceptance(client, body); err != nil {
+ return err
+ }
case 0x5c436609:
if err := server.handleMissionOffers(client, body); err != nil {
return err
diff --git a/server/mission_offers.go b/server/mission_offers.go
@@ -26,7 +26,13 @@ func missionOfferPacket(owner uint32, offer missionOffer) []byte {
body = binary.BigEndian.AppendUint32(body, word)
}
body = append(body, 1)
- for _, word := range []uint32{56003, offer.seed, 14, 0, 0, 32} {
+ body = appendMissionQuest(body, offer, offer.seed, 0, 48*60*60)
+ body = append(body, 0)
+ return n3Packet(0x5c436609, 50000, owner, body)
+}
+
+func appendMissionQuest(body []byte, offer missionOffer, id, owner, remaining uint32) []byte {
+ for _, word := range []uint32{56003, id, 14, 0, 0, 32} {
body = binary.BigEndian.AppendUint32(body, word)
}
body = append(body, 0)
@@ -37,7 +43,7 @@ func missionOfferPacket(owner uint32, offer missionOffer) []byte {
// Quest creator, RewardBox5 (cash/XP and empty item lists), and quest metadata.
for _, word := range []uint32{56001, offer.booth, 5, offer.definition.Credits, 0, offer.definition.Experience,
1009, 1009, 1009, 0, 0, 0, 0, 0, 0, 0,
- itemStat(gamedata.ItemTemplates[offer.definition.ObjectiveItem], 79), 0, 48 * 60 * 60, 2018} {
+ itemStat(gamedata.ItemTemplates[offer.definition.ObjectiveItem], 79), 0, remaining, 2018} {
body = binary.BigEndian.AppendUint32(body, word)
}
@@ -57,11 +63,19 @@ func missionOfferPacket(owner uint32, offer missionOffer) []byte {
body = append(body, action...)
// Owners, item vectors, text substitutions and the remaining Quest14 fields.
- for _, word := range []uint32{1009, 0, 0, 0, 6, 1009, 0, 0, 0, 0, 0, 0, 0, 0} {
+ owners := uint32(1009)
+ if owner != 0 {
+ owners = 2018
+ }
+ body = binary.BigEndian.AppendUint32(body, owners)
+ if owner != 0 {
+ body = binary.BigEndian.AppendUint32(body, 50000)
+ body = binary.BigEndian.AppendUint32(body, owner)
+ }
+ for _, word := range []uint32{0, 0, 0, 6, 1009, 0, 0, 0, 0, 0, 0, 0, 0} {
body = binary.BigEndian.AppendUint32(body, word)
}
- body = append(body, 0)
- return n3Packet(0x5c436609, 50000, owner, body)
+ return body
}
func (server *server) handleMissionOffers(client *worldClient, body []byte) error {
@@ -91,8 +105,9 @@ func (server *server) handleMissionOffers(client *worldClient, body []byte) erro
if exists {
originator, accepted = server.missionBoothEligibility_locked(client, booth)
}
- if !exists || !supported || !accepted || uint32(body[28]) != originator || player.inventory.Credits < uint32(player.level) {
+ if !exists || !supported || !accepted || uint32(body[28]) != originator || player.inventory.Credits < uint32(player.level) || len(player.missions) != 0 {
// The complete empty reply resets the native Generating Mission state.
+ client.missionOffer = nil
return client.send(n3Packet(0x5c436609, 50000, client.id, append([]byte(nil), body[16:]...)))
}
@@ -104,6 +119,7 @@ func (server *server) handleMissionOffers(client *worldClient, body []byte) erro
if err := server.saveInventory_locked(player, inventory); err != nil {
return err
}
+ client.missionOffer = &offer
cash := binary.BigEndian.AppendUint32(nil, 61)
cash = binary.BigEndian.AppendUint32(cash, inventory.Credits)
if err := client.send(n3Packet(0x2b333d6e, 50000, client.id, cash)); err != nil {
diff --git a/server/missions.go b/server/missions.go
@@ -0,0 +1,130 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "bytes"
+ "database/sql"
+ "encoding/binary"
+ "fmt"
+ "slices"
+ "strings"
+ "time"
+)
+
+type acceptedMission struct {
+ id uint32
+ owner uint32
+ offer missionOffer
+ expiresAt time.Time
+}
+
+const missionColumns = "owner_id, booth_id, seed, difficulty, dimension_0, dimension_1, dimension_2, dimension_3, dimension_4, dimension_5, originator, description, playfield, entrance, position_x, position_y, position_z, objective_item, credits, experience, expires_at"
+
+func (mission *acceptedMission) fields() []any {
+ return []any{&mission.owner, &mission.offer.booth, &mission.offer.seed, &mission.offer.difficulty,
+ &mission.offer.dimensions[0], &mission.offer.dimensions[1], &mission.offer.dimensions[2], &mission.offer.dimensions[3], &mission.offer.dimensions[4], &mission.offer.dimensions[5],
+ &mission.offer.originator, &mission.offer.definition.Description, &mission.offer.definition.Playfield, &mission.offer.definition.Entrance,
+ &mission.offer.definition.Position[0], &mission.offer.definition.Position[1], &mission.offer.definition.Position[2],
+ &mission.offer.definition.ObjectiveItem, &mission.offer.definition.Credits, &mission.offer.definition.Experience, &mission.expiresAt}
+}
+
+func insertMission(tx *sql.Tx, mission *acceptedMission) error {
+ // The accepted contract and its first key commit with inventory ownership.
+ var saved uint32
+ query := "INSERT INTO missions (id, " + missionColumns + ") VALUES (?" + strings.Repeat(", ?", len(mission.fields())) + ") RETURNING id"
+ if err := tx.QueryRow(query, append([]any{mission.id}, mission.fields()...)...).Scan(&saved); err != nil {
+ return fmt.Errorf("save mission %d: %w", mission.id, err)
+ }
+ if err := tx.QueryRow("INSERT INTO mission_keys (item_id, mission_id) VALUES (?, ?) RETURNING item_id", mission.id, mission.id).Scan(&saved); err != nil {
+ return fmt.Errorf("save mission %d key: %w", mission.id, err)
+ }
+ return nil
+}
+
+func (server *server) loadMissions() error {
+ rows, err := server.db.Query("SELECT id, " + missionColumns + " FROM missions ORDER BY id")
+ if err != nil {
+ return err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var mission acceptedMission
+ if err := rows.Scan(append([]any{&mission.id}, mission.fields()...)...); err != nil {
+ return err
+ }
+ player := server.characters[mission.owner]
+ player.missions = append(player.missions, mission)
+ }
+ return rows.Err()
+}
+
+func missionJournalPacket(mission acceptedMission, now time.Time) []byte {
+ // Original QuestFullUpdate1: category1 is an assigned mission, followed by Quest14.
+ body := binary.BigEndian.AppendUint32(nil, 1)
+ body = binary.BigEndian.AppendUint32(body, 1)
+ remaining := uint32(max(0, mission.expiresAt.Sub(now).Seconds()))
+ body = appendMissionQuest(body, mission.offer, mission.id, mission.owner, remaining)
+ return n3Packet(0x465a4061, 50000, mission.owner, body)
+}
+
+func (server *server) handleMissionAcceptance(client *worldClient, body []byte) error {
+ if len(body) != 38 || body[16] != 2 || body[37] != 0 {
+ return nil
+ }
+ server.updateMutex.Lock()
+ defer server.updateMutex.Unlock()
+ server.mutex.Lock()
+ defer server.mutex.Unlock()
+ player := server.characters[client.id]
+ if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 ||
+ binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || client.missionOffer == nil || len(player.missions) != 0 {
+ return nil
+ }
+ offer := *client.missionOffer
+ if body[17] != offer.difficulty || !bytes.Equal(body[18:24], offer.dimensions[:]) || binary.BigEndian.Uint32(body[24:28]) != offer.seed ||
+ body[28] != offer.originator || binary.BigEndian.Uint32(body[29:33]) != 56001 || binary.BigEndian.Uint32(body[33:37]) != offer.booth {
+ return nil
+ }
+ booth, exists := gamedata.MissionBooths[offer.booth]
+ if !exists {
+ return nil
+ }
+ if _, accepted := server.missionBoothEligibility_locked(client, booth); !accepted {
+ return nil
+ }
+
+ // Stage a new key and immutable contract without allocating live identities.
+ if server.nextItem == ^uint32(0) {
+ return fmt.Errorf("item identities exhausted")
+ }
+ slot := uint32(64)
+ for slices.ContainsFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == slot }) {
+ slot++
+ }
+ key := ownedItem{ID: server.nextItem + 1, Type: 51053, Template: 28577, Quality: 1, Slot: slot, Count: 1}
+ inventory := player.inventory
+ inventory.LastID = key.ID
+ inventory.Items = append(slices.Clone(inventory.Items), key)
+ mission := acceptedMission{id: key.ID, owner: player.id, offer: offer, expiresAt: time.Now().UTC().Add(48 * time.Hour)}
+ store, err := server.itemStore_locked(player, inventory)
+ if err != nil {
+ return err
+ }
+ store.mission = &mission
+ if err := server.writeItemStore_locked(store); err != nil {
+ return err
+ }
+ player.inventory = inventory
+ player.missions = append(player.missions, mission)
+ client.missionOffer = nil
+
+ // Add the native template proxy only after the key and journal are durable.
+ var addition []byte
+ for _, value := range []uint32{key.Template, key.Template, key.Quality, uint32(key.Count)} {
+ addition = binary.BigEndian.AppendUint32(addition, value)
+ }
+ if err := client.send(n3Packet(0x052e2f0c, 50000, client.id, addition)); err != nil {
+ return err
+ }
+ return client.send(missionJournalPacket(mission, time.Now()))
+}
diff --git a/server/missions_test.go b/server/missions_test.go
@@ -0,0 +1,325 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "net"
+ "reflect"
+ "sync"
+ "testing"
+ "time"
+)
+
+func missionAcceptanceRequest(offer missionOffer) []byte {
+ body := missionOffersRequest()
+ binary.BigEndian.PutUint32(body, 0x291f361b)
+ body[16], body[17], body[28] = 2, offer.difficulty, offer.originator
+ copy(body[18:24], offer.dimensions[:])
+ binary.BigEndian.PutUint32(body[24:28], offer.seed)
+ binary.BigEndian.PutUint32(body[33:37], offer.booth)
+ return body
+}
+
+func TestMissionAcceptanceNativeDispatchCommitsKeyAndJournal(t *testing.T) {
+ newMissionOfferWorld(t)
+ world := newTestInventoryServer(t)
+ connection := connectZoningClient(t, world, true)
+ defer connection.Close()
+ request := missionOffersRequest()
+ if _, err := connection.Write(targetPacket(n3Packet(0x5c436609, 50000, 1, request[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 := append([]byte(nil), offer[29:51]...)
+ selection[0], selection[21] = 2, 0
+
+ if _, err := connection.Write(targetPacket(n3Packet(0x291f361b, 50000, 1, selection))); 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).characters[1]
+ var bindings int
+ err = world.db.QueryRow("SELECT count(*) FROM mission_keys JOIN missions ON missions.id=mission_keys.mission_id JOIN item_locations USING(item_id) WHERE missions.owner_id=1 AND item_locations.player_id=1").Scan(&bindings)
+
+ if err != nil || bindings != 1 || len(cold.missions) != 1 || len(cold.inventory.Items) != 2 || cold.inventory.Credits != 4 || cold.experience != 0 {
+ t.Fatalf("acceptance lost contract/key, charged again or granted rewards: %+v %v", cold.inventory, err)
+ }
+ if cold.inventory.Items[1] != (ownedItem{ID: 2, Type: 51053, Template: 28577, Quality: 1, Slot: 65, Count: 1}) || cold.missions[0].id != 2 || cold.missions[0].owner != 1 ||
+ cold.missions[0].offer.definition.Entrance != 3221228472 || cold.missions[0].offer.definition.Playfield != 3000 {
+ t.Fatal("acceptance did not retain the assigned exterior and exact key instance")
+ }
+ if binary.BigEndian.Uint32(key[16:20]) != 0x052e2f0c || binary.BigEndian.Uint32(key[29:33]) != 28577 ||
+ binary.BigEndian.Uint32(journal[16:20]) != 0x465a4061 || !bytes.Equal(journal[29:45], []byte{0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0xda, 0xc3, 0, 0, 0, 2}) {
+ t.Fatalf("wrong native key/journal publication: %x %x", key, journal)
+ }
+}
+
+func TestMissionAcceptanceRejectsChangedOrStaleOffers(t *testing.T) {
+ for _, scenario := range []string{"short", "long", "version", "selection", "difficulty", "dimension", "seed", "origin", "booth type", "booth id", "subject type", "subject id",
+ "no offer", "regenerated", "failed generation", "dead", "loading", "not ready", "stale session", "legacy", "far", "other playfield", "equipment", "trade", "one free slot"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, output := newMissionOfferWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+ request := missionAcceptanceRequest(*client.missionOffer)
+ switch scenario {
+ case "short":
+ request = request[:37]
+ case "long":
+ request = append(request, 0)
+ case "version":
+ request[16] = 1
+ case "selection":
+ request[37] = 1
+ case "difficulty":
+ request[17]++
+ case "dimension":
+ request[18] = 1
+ case "seed":
+ request[24] ^= 1
+ case "origin":
+ request[28] = 3
+ case "booth type":
+ binary.BigEndian.PutUint32(request[29:33], 56006)
+ case "booth id":
+ binary.BigEndian.PutUint32(request[33:37], 3221228509)
+ case "subject type":
+ binary.BigEndian.PutUint32(request[4:8], 56003)
+ case "subject id":
+ binary.BigEndian.PutUint32(request[8:12], 2)
+ case "no offer":
+ client.missionOffer = nil
+ case "regenerated":
+ if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+ case "failed generation":
+ other := missionOffersRequest()
+ binary.BigEndian.PutUint32(other[33:37], 42)
+ if err := world.handleMissionOffers(client, other); err != nil {
+ t.Fatal(err)
+ }
+ case "dead":
+ player.health = 0
+ case "loading":
+ client.loading = true
+ case "not ready":
+ client.ready = false
+ case "stale session":
+ world.clients[1] = &worldClient{id: 1}
+ case "legacy":
+ client.target = false
+ case "far":
+ player.position[0] = 110
+ case "other playfield":
+ player.playfield = 3037
+ case "equipment":
+ client.equipment = &equipmentMove{}
+ case "trade":
+ client.trade = &playerTrade{}
+ case "one free slot":
+ for slot := uint32(64); slot < 93; slot++ {
+ player.inventory.Items = append(player.inventory.Items, ownedItem{Slot: slot})
+ }
+ }
+ output.packets = nil
+ before := player.inventory
+
+ err := world.handleMissionAcceptance(client, request)
+ cold := newTestInventoryServer(t).characters[1]
+
+ if err != nil || len(output.packets) != 0 || len(player.missions) != 0 || len(cold.missions) != 0 || len(cold.inventory.Items) != 1 ||
+ !reflect.DeepEqual(before, player.inventory) || cold.inventory.Credits != before.Credits || world.nextItem != 1 {
+ t.Fatal("invalid acceptance changed inventory, journal or durable state", err)
+ }
+ })
+ }
+}
+
+func TestMissionAcceptanceFailureRollsBackKeyAndContractThenRetries(t *testing.T) {
+ for _, table := range []string{"items", "item_locations", "missions", "mission_keys"} {
+ for _, failure := range []string{"ABORT", "IGNORE", "commit"} {
+ t.Run(table+"/"+failure, func(t *testing.T) {
+ world, output := newMissionOfferWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+ request := missionAcceptanceRequest(*client.missionOffer)
+ statement := fmt.Sprintf("CREATE TRIGGER fail_accept BEFORE INSERT ON %s BEGIN SELECT RAISE(%s, 'acceptance'); END", table, failure)
+ if failure == "IGNORE" {
+ statement = fmt.Sprintf("CREATE TRIGGER fail_accept BEFORE INSERT ON %s BEGIN SELECT RAISE(IGNORE); END", table)
+ }
+ if failure == "commit" {
+ statement = fmt.Sprintf("CREATE TABLE pending_accept (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_accept AFTER INSERT ON %s BEGIN INSERT INTO pending_accept VALUES (999999); END", table)
+ }
+ if _, err := world.db.Exec(statement); err != nil {
+ t.Fatal(err)
+ }
+ output.packets = nil
+
+ err := world.handleMissionAcceptance(client, request)
+ cold := newTestInventoryServer(t).characters[1]
+
+ if err == nil || len(output.packets) != 0 || len(player.missions) != 0 || len(cold.missions) != 0 || len(cold.inventory.Items) != 1 || len(player.inventory.Items) != 1 ||
+ world.nextItem != 1 || client.missionOffer == nil || player.inventory.Credits != 4 || cold.inventory.Credits != 4 {
+ t.Fatal("failed acceptance published state, consumed offer or lost committed fee", err)
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_accept"); err != nil {
+ t.Fatal(err)
+ }
+
+ err = world.handleMissionAcceptance(client, request)
+ cold = newTestInventoryServer(t).characters[1]
+
+ if err != nil || len(output.packets) != 2 || len(player.missions) != 1 || len(cold.missions) != 1 || len(cold.inventory.Items) != 2 || len(player.inventory.Items) != 2 ||
+ world.nextItem != 2 || client.missionOffer != nil || cold.inventory.Items[1].ID != 2 {
+ t.Fatal("acceptance retry did not commit exactly one contract and key", err)
+ }
+ })
+ }
+ }
+}
+
+func TestMissionAcceptanceConcurrentReplayAndNewGenerationCannotDuplicate(t *testing.T) {
+ world, output := newMissionOfferWorld(t)
+ client := world.clients[1]
+ if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+ request := missionAcceptanceRequest(*client.missionOffer)
+ output.packets = nil
+ var pending sync.WaitGroup
+ failures := make(chan error, 2)
+
+ for range 2 {
+ pending.Add(1)
+ go func() {
+ defer pending.Done()
+ failures <- world.handleMissionAcceptance(client, request)
+ }()
+ }
+ pending.Wait()
+ close(failures)
+ if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t).characters[1]
+
+ for err := range failures {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ if len(cold.missions) != 1 || len(cold.inventory.Items) != 2 || cold.inventory.Credits != 4 || world.nextItem != 2 || len(output.packets) != 3 || output.packets[2][50] != 0 {
+ t.Fatal("concurrent/repeated acceptance or a second training mission duplicated state or charged again")
+ }
+}
+
+func TestAcceptedMissionSurvivesEditsAndColdOwnerOnlyReplay(t *testing.T) {
+ world, _ := newMissionOfferWorld(t)
+ client := world.clients[1]
+ request := missionOffersRequest()
+ request[17] = 11
+ copy(request[18:24], []byte{156, 100, 255, 0, 1, 99})
+ if err := world.handleMissionOffers(client, request); err != nil {
+ t.Fatal(err)
+ }
+ definition := gamedata.MissionTemplates[3221228472]
+ t.Cleanup(func() { gamedata.MissionTemplates[3221228472] = definition })
+ gamedata.MissionTemplates[3221228472] = gamedata.MissionTemplate{Description: "changed after generation"}
+ if err := world.handleMissionAcceptance(client, missionAcceptanceRequest(*client.missionOffer)); err != nil {
+ t.Fatal(err)
+ }
+ original := world.characters[1].missions[0]
+ destination := world.characters[1].userData()
+ destination.Name, destination.Playfield = "Mission Owner", 800
+ world.nextCharacter = 1
+ otherPlayer := world.newCharacter()
+ if err := world.saveInventory_locked(otherPlayer, otherPlayer.inventory); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := world.updateUser(destination); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.saveInventory_locked(world.characters[1], world.characters[1].inventory); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.flushPositions(time.Now().Add(time.Minute)); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+ owner := captureMissionReplay(t, cold, 1)
+ other := captureMissionReplay(t, cold, 2)
+
+ if len(world.characters[1].missions) != 1 || world.characters[1].missions[0] != original || len(cold.characters[1].missions) != 1 || cold.characters[1].missions[0] != original ||
+ len(owner) != 1 || len(other) != 0 || len(cold.characters[2].missions) != 0 || !bytes.Contains(owner[0], []byte("Recover the Blue Book of Secrets\n")) || bytes.Contains(owner[0], []byte("changed after generation")) {
+ t.Fatal("edit/checkpoint/restart changed the accepted contract or leaked its journal")
+ }
+}
+
+func TestMissionAcceptanceOutputFailureRetainsOneCommittedContract(t *testing.T) {
+ world, output := newMissionOfferWorld(t)
+ client := world.clients[1]
+ if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+ request := missionAcceptanceRequest(*client.missionOffer)
+ output.packets = nil
+ client.writeWake, client.writeClosed = make(chan struct{}, 1), true
+
+ err := world.handleMissionAcceptance(client, request)
+ retry := world.handleMissionAcceptance(client, request)
+ cold := newTestInventoryServer(t)
+ journal := captureMissionReplay(t, cold, 1)
+
+ if err != net.ErrClosed || retry != nil || len(output.packets) != 0 || client.missionOffer != nil || len(journal) != 1 ||
+ len(cold.characters[1].missions) != 1 || len(cold.characters[1].inventory.Items) != 2 || cold.characters[1].inventory.Credits != 4 || cold.nextItem != 2 {
+ t.Fatal("lost output rolled back or duplicated the committed mission/key", err, retry)
+ }
+}
+
+func captureMissionReplay(t *testing.T, world *server, owner uint32) [][]byte {
+ t.Helper()
+ connection, peer := net.Pipe()
+ defer connection.Close()
+ connection.SetDeadline(time.Now().Add(5 * time.Second))
+ go func() { defer peer.Close(); world.serveWorldConnection(peer) }()
+ cookie := systemPacket(0x1b, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})
+ binary.BigEndian.PutUint16(cookie, 0xdfdf)
+ binary.BigEndian.PutUint32(cookie[20:24], owner)
+ if _, err := connection.Write(cookie); err != nil {
+ t.Fatal(err)
+ }
+ var result [][]byte
+ for {
+ packet, err := readPacket(connection)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x465a4061 {
+ result = append(result, packet)
+ }
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x5f52412e {
+ return result
+ }
+ }
+}
diff --git a/server/state.go b/server/state.go
@@ -32,6 +32,7 @@ type character struct {
combatProfile *gamedata.NPCCombatProfile
team *playerTeam
buddies map[uint32]string
+ missions []acceptedMission
health uint32
nano uint32
nanoReserved uint32
@@ -93,6 +94,7 @@ type worldClient struct {
useSequence uint32
selectedTarget [2]uint32
teamInvitation *teamInvitation
+ missionOffer *missionOffer
absorbedBonuses map[uint32]resourceBonuses
}
diff --git a/server/users.go b/server/users.go
@@ -156,6 +156,9 @@ func (server *server) loadUsers() error {
if err := server.loadItems(); err != nil {
return err
}
+ if err := server.loadMissions(); 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 {
diff --git a/server/world.sql b/server/world.sql
@@ -214,6 +214,28 @@ CREATE UNIQUE INDEX IF NOT EXISTS player_slots ON item_locations(player_id, slot
CREATE UNIQUE INDEX IF NOT EXISTS bank_slots ON item_locations(bank_player_id, slot);
CREATE UNIQUE INDEX IF NOT EXISTS backpack_slots ON item_locations(backpack_id, slot);
CREATE UNIQUE INDEX IF NOT EXISTS corpse_slots ON item_locations(corpse_id, slot);
+CREATE TABLE IF NOT EXISTS missions (
+ id INTEGER PRIMARY KEY CHECK (id BETWEEN 1 AND 4294967295),
+ owner_id INTEGER NOT NULL REFERENCES players(id) ON DELETE CASCADE,
+ booth_id INTEGER NOT NULL,
+ seed INTEGER NOT NULL,
+ difficulty INTEGER NOT NULL,
+ dimension_0 INTEGER NOT NULL, dimension_1 INTEGER NOT NULL, dimension_2 INTEGER NOT NULL,
+ dimension_3 INTEGER NOT NULL, dimension_4 INTEGER NOT NULL, dimension_5 INTEGER NOT NULL,
+ originator INTEGER NOT NULL,
+ description TEXT NOT NULL,
+ playfield INTEGER NOT NULL,
+ entrance INTEGER NOT NULL,
+ position_x REAL NOT NULL, position_y REAL NOT NULL, position_z REAL NOT NULL,
+ objective_item INTEGER NOT NULL,
+ credits INTEGER NOT NULL,
+ experience INTEGER NOT NULL,
+ expires_at DATETIME NOT NULL
+);
+CREATE TABLE IF NOT EXISTS mission_keys (
+ item_id INTEGER PRIMARY KEY REFERENCES items(id) ON DELETE CASCADE,
+ mission_id INTEGER NOT NULL REFERENCES missions(id) ON DELETE CASCADE
+);
CREATE TABLE IF NOT EXISTS chat_history (
id INTEGER PRIMARY KEY,
owner INTEGER NOT NULL,