aorecomp

Anarchy Online classic in the browser

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


commit ebff29d4cb0c1cbb928881efddfe4cc088ef7c78
parent e91dd574e67c04cf88cf57b2bc045ad75c09b9f5
Author: anon <anon@example.com>
Date:   Tue, 27 Oct 2026 05:52:54 +0000

Deliver native starter mission offers

Diffstat:
MTODO.md | 32+++++++++++++++++++++++++-------
Adocs/mission-offers.md | 111+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mdocs/mission-terminals.md | 6++++--
Mserver/gamedata/load.go | 2++
Mserver/gamedata/mission_booths_test.go | 14++++++++++++++
Aserver/gamedata/missions.yaml | 14++++++++++++++
Mserver/gamedata/types.go | 9+++++++++
Mserver/main.go | 4++++
Mserver/mission_booths.go | 49+++++++++++++++++++++++++++++--------------------
Aserver/mission_offers.go | 113+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_offers_test.go | 311+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
11 files changed, 636 insertions(+), 29 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -57,8 +57,8 @@ 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). -Quest and mission checkboxes below -are still open; they have not been implemented by the shop or dialogue work. +Complete quest and mission progression remains open; opening a booth and browsing +an offer do not yet provide accepted contracts, objectives or mission rewards. 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. @@ -1361,15 +1361,23 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). The catalog retains392 authored booths and their statel overrides, excluding seven test displays. Go checks cover native socket dispatch, template faction/ level gates, team/free-slot requirements, range, session and packet rejection. - Real GPU WASM interaction now opens the native window; offers remain open. + Real GPU WASM interaction now opens the native window. See [mission terminals](docs/mission-terminals.md). -- [ ] [P1] Browse one mission terminal offer. Check: its native details and location +- [x] Browse one mission terminal offer. Check: its native details and location render correctly without accepting it automatically. - Recover the complete native QuestAlternative/Quest_t offer serialization; - keep browsing distinct from CreateQuest acceptance. Preserve authored style - selectors rather than interpreting them as playfield IDs or faction numbers. + QuestAlternative4/Quest14, RewardBox5 and Action19 now deliver one fixed + provisional Blue Book contract from the backyard3000 booth. GPU WASM + verifies its icon, details, cash/XP display and exterior map marker. Generation + commits the level-credit fee before publication; failed writes, signed slider + bounds, invalid contexts and concurrent affordability are covered by Go tests. + 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 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. - [ ] [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, @@ -1380,10 +1388,20 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). Commit completion with XP, credits and any item reward atomically through the shared progression/inventory paths. Verify full inventory, duplicate completion, failed writes/commit, disconnect and restart without lost or repeated rewards. +- [ ] [P1] Recover objective completion and token/XP eligibility rules. Action19 + matches the objective item's template/QL, but its pickup/inspection/return + 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] 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. + Current browsing validates and echoes these settings but returns one fixed + contract. Recover level/QL, objective, reward and population selection rules; + preserve authored style selectors instead of treating them as playfield IDs + or faction numbers. Verify distinct settings and original boundary behavior. ## Teams diff --git a/docs/mission-offers.md b/docs/mission-offers.md @@ -0,0 +1,111 @@ +# Mission offers + +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. + +## Content and scope + +`server/gamedata/missions.yaml` defines a fixed Blue Book of Secrets contract +for booth56001/3221228472. Its objective uses original QL1 item40822 and its +destination uses the nearby Surveillance Office entrance56006/3221228472 in +playfield3000 at89.302162,115.144440,151.160873. The objective item's original +payload SHA256 is +`645b946ec12830a3695e1c27659dc37676dbc2b884cb1f19e4fda1692e7066fe`. +The original item and exterior placement establish those assets, not a recovered +complete contract. The narrative, displayed20 credits/100 XP and48-hour duration +are provisional reconstruction choices. No private interior is assigned yet. + +The authored booth catalog and shared template Use criteria still control +admission. Both opening and generating use the same playfield, five-metre +distance, equipment/trade, team, free-slot and template eligibility checks. +Only this booth has offer content. A valid request without eligible content or +enough credits receives a complete empty selection reply and incurs no fee. +Malformed, foreign or stale-session requests produce no offer. + +Difficulty1..11 and six signed dimensions in[-100,100] are validated and echoed. +They do not yet change this fixed content, its quality or its rewards. Style +selectors remain authored data, not invented destination IDs. + +## Native protocol and evidence + +REA/Ghidra12.1.2 observations of the original binaries and full provenance are +retained in `local/mission-offers/kkr-evidence.json` and `ddr-evidence.json`. +Recovered pseudocode needs native corroboration; it is not original source. +`kkr.dll` SHA256 is +`241b2e665dcd127399b7686cddda8a5b0876d9cde9b3af7a73940dd0b86ecaa7`; +`ddr.dll` SHA256 is +`7e8f49d5fca11a601febece4f9bbb93acbaf0cbad2ca75bd8f4e3891944cbf50`. + +QuestAlternative0x5c436609/version4 contains difficulty, six signed dimensions, +seed, originator and booth identity, then an offer count. Each offer carries +quest identity56003/seed, a complete Quest14 record and a selection byte. The +serializer includes the NUL-terminated description, RewardBox5, Action19 and +all empty lists/trailing fields. Native empty encoded lists use1009. RewardBox5 +holds cash at offset+8 and XP at+12 in the recovered native object. + +Action19 matches item template and QL; its serialized WorldPos at offset108 +supplies playfield identity40016/3000, integer origins and local XYZ. Original +`kkr.dll!0x360c5960` establishes item matching and0x36027ab0 reads the first +action's position for coordinate upload. This does not establish whether the +objective completes on pickup, inspection or return. A native map check confirms +the displayed exterior marker; no geometry-to-private-interior mapping is claimed. + +`ddr.dll!0x2b086450` requires Cash/stat61 at least Level/stat54 before requesting +a mission and checks two free slots (evidence +`ev_fddab598e19ab179caf9cf2458edfda9246bf36e243fe667685a3aba96a484bd`). +The server charges Level credits for a supported generation, committing the +wallet before sending Cash and the offer. The native code proves the +affordability precheck; the corresponding original server debit was not captured. +The chosen fee is a reconstruction consistent with that precheck. + +`ddr.dll!0x2b0867b0` selects an offer and uploads coordinates without accepting. +`kkr.dll!0x360217c0` expands the native selection-list identity/index/seed layout; +0x36021ac0 constructs CreateQuest. Clicking Accept in the real client captured +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. + +## Verification + +The focused Go run passed14 roots/104 test results across offer serialization, +native socket dispatch, admission, fee persistence failures/retry, booth tests, +original asset linkage and adjacent bank/shop/insurance/door regressions. +The separate concurrent-request test verifies that two requests with one credit +produce one charged offer and one empty rejection, with a cold balance of zero. +Failure injection covers aborted writes, ignored updates and failed commits. +Every signed dimension axis is checked at-101,-100,100,101. Difficulty endpoints, +level-based affordability and all three destination coordinates are checked. +The full gamedata package also passed. + +Headed Chromium using the GPU and real WASM client displayed the book icon, +description, cash20/XP100 and an uploaded map marker northwest of the player at +the authored entrance. The details also say XP is received with a token; +token eligibility and settlement remain open. Dragging native advanced sliders +captured difficulty11 and dimension0=-100. Three generations reduced a controlled +five-credit fixture to two credits. SQL snapshots and a cold restart/reconnect +without fixture edits retained level1, XP0, two credits and no items. The native +accepted journal stayed empty after browsing, cancellation and the unimplemented +Accept request. These controlled funds do not establish an earned-income loop. + +Moving away closed the native selection window automatically. The later click +at its former Request position did not send a generation request, so it is not +claimed as a manual server-range rejection; direct Go tests cover that rejection. +Page exception lists remained empty and no adapter crash was observed. Startup +logged HTTP404 responses whose URLs were not identified; this does not establish +a completely error-free page load. Wire captures, screenshots and accounting are +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 +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 +and inventory paths. See [remaining integration](mission-terminals.md#remaining-integration) +and the Missions section of `TODO.md`. diff --git a/docs/mission-terminals.md b/docs/mission-terminals.md @@ -111,8 +111,10 @@ include description, rewards, world position, actions and multiple lists; empty identity lists use the native1009 count encoding. Returning only an icon or invented short payload cannot establish a usable offer. -These observations do not yet establish complete reward/objective semantics, -canonical generated content or a fully tested offer serializer. The original +The initial observations above preceded the complete offer serializer. The +implemented fixed offer and its native validation are documented in +[mission offers](mission-offers.md). Complete reward/objective semantics and +canonical generated content remain unresolved. The original shipped `The Mission Window.txt` confirms difficulty selection, accepted journal entries, details, coordinate upload and duplicating mission keys. Original key28577 and duplicator28564 descriptions also establish key-based admission; diff --git a/server/gamedata/load.go b/server/gamedata/load.go @@ -31,6 +31,7 @@ var ( Playfields map[uint32]Playfield ShopMachines map[uint32]ShopMachine MissionBooths map[uint32]MissionBooth + MissionTemplates map[uint32]MissionTemplate ShopStock map[uint32][]uint32 ItemCombinations map[uint32]map[uint32]ItemCombination PlayerAppearances struct { @@ -83,6 +84,7 @@ func init() { loadYAML("banks.yaml", &BankTerminals) loadYAML("shops.yaml", &ShopMachines) loadYAML("mission_booths.yaml", &MissionBooths) + loadYAML("missions.yaml", &MissionTemplates) loadYAML("shop_stock.yaml", &ShopStock) loadYAML("profession_resources.yaml", &ProfessionTitles) loadYAML("experience.yaml", &ExperienceLevels) diff --git a/server/gamedata/mission_booths_test.go b/server/gamedata/mission_booths_test.go @@ -80,3 +80,17 @@ func TestStarterMissionBoothsRetainAuthoredSelectors(t *testing.T) { }) } } + +func TestStarterMissionTemplateReferencesOriginalAssets(t *testing.T) { + definition := MissionTemplates[3221228472] + booth := MissionBooths[3221228472] + + item := ItemTemplates[definition.ObjectiveItem] + + if definition.Playfield != booth.Playfield || definition.Playfield != 3000 || + definition.Position != [3]float32{89.30216217041016, 115.14443969726562, 151.16087341308594} || + item == nil || item.ID != 40822 || item.Quality == nil || *item.Quality != 1 || + item.PayloadSHA256 != "645b946ec12830a3695e1c27659dc37676dbc2b884cb1f19e4fda1692e7066fe" { + t.Fatal("starter mission lost its original entrance position or objective asset") + } +} diff --git a/server/gamedata/missions.yaml b/server/gamedata/missions.yaml @@ -0,0 +1,14 @@ +# Fixed starter reconstruction; narrative and rewards are provisional. +# Exterior position: original 14.9.1 Surveillance Office, type56006/3221228472. +# Objective: original QL1 Blue Book of Secrets40822, a documented mission item. +3221228472: + description: |- + Recover the Blue Book of Secrets + + 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 + position: [89.30216217041016, 115.14443969726562, 151.16087341308594] + objective_item: 40822 + credits: 20 + experience: 100 diff --git a/server/gamedata/types.go b/server/gamedata/types.go @@ -15,6 +15,15 @@ type MissionBooth struct { Stats [][2]uint32 `yaml:"stats"` } +type MissionTemplate struct { + Description string `yaml:"description"` + Playfield uint32 `yaml:"playfield"` + Position [3]float32 `yaml:"position"` + ObjectiveItem uint32 `yaml:"objective_item"` + Credits uint32 `yaml:"credits"` + Experience uint32 `yaml:"experience"` +} + type ItemCombination struct { Result uint32 `yaml:"result"` Skills [][2]uint32 `yaml:"skills,flow"` diff --git a/server/main.go b/server/main.go @@ -492,6 +492,10 @@ func (server *server) serveWorldClient(client *worldClient) error { decodeInventory1491(body) } switch binary.BigEndian.Uint32(body[0:4]) { + case 0x5c436609: + if err := server.handleMissionOffers(client, body); err != nil { + return err + } case 0x3b290771: if err := server.handleSocialAction(client, body); err != nil { return err diff --git a/server/mission_booths.go b/server/mission_booths.go @@ -6,6 +6,32 @@ import ( "time" ) +func (server *server) missionBoothEligibility_locked(client *worldClient, booth gamedata.MissionBooth) (uint32, bool) { + player := server.characters[client.id] + if player.playfield != booth.Playfield || client.equipment != nil || client.trade != nil { + return 0, false + } + position := predictedPosition_locked(player, time.Now()) + x, y, z := position[0]-booth.Position[0], position[1]-booth.Position[1], position[2]-booth.Position[2] + definition := gamedata.ItemTemplates[booth.Template] + accepted := x*x+y*y+z*z <= 5*5 && itemStat(definition, 30)&8 != 0 && player.templateUseRequirementsMet(definition) + originator := itemStat(definition, 490) + for _, stat := range booth.Stats { + if stat[0] == 490 { + originator = stat[1] + } + } + + // QuestBooth::Use requires two free inventory slots and a team for even origins. + free := 30 + for _, item := range player.inventory.Items { + if item.Slot >= 64 { + free-- + } + } + return originator, accepted && free >= 2 && (originator%2 != 0 || player.team != nil) +} + func (server *server) handleMissionBoothUse(client *worldClient, body []byte) error { if len(body) != 48 { return nil @@ -30,26 +56,9 @@ func (server *server) handleMissionBoothUse(client *worldClient, body []byte) er // Validate the authored object and its Use criteria before the native callback. booth, exists := gamedata.MissionBooths[binary.BigEndian.Uint32(body[44:48])] - accepted := exists && player.playfield == booth.Playfield && client.equipment == nil && client.trade == nil - if accepted { - position := predictedPosition_locked(player, time.Now()) - x, y, z := position[0]-booth.Position[0], position[1]-booth.Position[1], position[2]-booth.Position[2] - definition := gamedata.ItemTemplates[booth.Template] - accepted = x*x+y*y+z*z <= 5*5 && itemStat(definition, 30)&8 != 0 && player.templateUseRequirementsMet(definition) - originator := itemStat(definition, 490) - for _, stat := range booth.Stats { - if stat[0] == 490 { - originator = stat[1] - } - } - // QuestBooth::Use requires two free inventory slots and a team for even origins. - free := 30 - for _, item := range player.inventory.Items { - if item.Slot >= 64 { - free-- - } - } - accepted = accepted && free >= 2 && (originator%2 != 0 || player.team != nil) + accepted := false + if exists { + _, accepted = server.missionBoothEligibility_locked(client, booth) } // Opening the difficulty window does not accept a mission or grant rewards. diff --git a/server/mission_offers.go b/server/mission_offers.go @@ -0,0 +1,113 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "math" + "math/rand/v2" +) + +type missionOffer struct { + seed uint32 + booth uint32 + difficulty byte + dimensions [6]byte + originator byte + definition gamedata.MissionTemplate +} + +func missionOfferPacket(owner uint32, offer missionOffer) []byte { + // QuestAlternative4 carries the ACG request parameters and one unaccepted quest. + body := []byte{4, offer.difficulty} + body = append(body, offer.dimensions[:]...) + body = binary.BigEndian.AppendUint32(body, offer.seed) + body = append(body, offer.originator) + for _, word := range []uint32{56001, offer.booth} { + body = binary.BigEndian.AppendUint32(body, word) + } + body = append(body, 1) + for _, word := range []uint32{56003, offer.seed, 14, 0, 0, 32} { + body = binary.BigEndian.AppendUint32(body, word) + } + body = append(body, 0) + body = binary.BigEndian.AppendUint32(body, uint32(len(offer.definition.Description)+1)) + body = append(body, offer.definition.Description...) + body = append(body, 0) + + // 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} { + body = binary.BigEndian.AppendUint32(body, word) + } + + // Action19 matches an item template and quality range. Its WorldPos supplies + // the exterior map/compass location independently of private interior geometry. + action := make([]byte, 136) + binary.BigEndian.PutUint32(action[0:4], 19) + binary.BigEndian.PutUint32(action[4:8], offer.definition.ObjectiveItem) + binary.BigEndian.PutUint32(action[8:12], offer.definition.ObjectiveItem) + binary.BigEndian.PutUint32(action[12:16], 1) + binary.BigEndian.PutUint32(action[16:20], 1) + binary.BigEndian.PutUint32(action[108:112], 40016) + binary.BigEndian.PutUint32(action[112:116], offer.definition.Playfield) + for index, position := range offer.definition.Position { + binary.BigEndian.PutUint32(action[124+index*4:], math.Float32bits(position)) + } + 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} { + body = binary.BigEndian.AppendUint32(body, word) + } + body = append(body, 0) + return n3Packet(0x5c436609, 50000, owner, body) +} + +func (server *server) handleMissionOffers(client *worldClient, body []byte) error { + if len(body) != 38 || body[16] != 4 || body[17] < 1 || body[17] > 11 || body[28] < 1 || body[28] > 8 || body[37] != 0 || + binary.BigEndian.Uint32(body[24:28]) != 0 || binary.BigEndian.Uint32(body[29:33]) != 56001 { + return nil + } + for _, dimension := range body[18:24] { + if int8(dimension) < -100 || int8(dimension) > 100 { + 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 { + return nil + } + boothID := binary.BigEndian.Uint32(body[33:37]) + booth, exists := gamedata.MissionBooths[boothID] + definition, supported := gamedata.MissionTemplates[boothID] + var originator uint32 + accepted := false + if exists { + originator, accepted = server.missionBoothEligibility_locked(client, booth) + } + if !exists || !supported || !accepted || uint32(body[28]) != originator || player.inventory.Credits < uint32(player.level) { + // The complete empty reply resets the native Generating Mission state. + return client.send(n3Packet(0x5c436609, 50000, client.id, append([]byte(nil), body[16:]...))) + } + + // Charge only a validated generation, committing the wallet before its reply. + offer := missionOffer{seed: rand.Uint32N(math.MaxUint32) + 1, booth: boothID, difficulty: body[17], originator: body[28], definition: definition} + copy(offer.dimensions[:], body[18:24]) + inventory := player.inventory + inventory.Credits -= uint32(player.level) + if err := server.saveInventory_locked(player, inventory); err != nil { + return err + } + 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 { + return err + } + return client.send(missionOfferPacket(client.id, offer)) +} diff --git a/server/mission_offers_test.go b/server/mission_offers_test.go @@ -0,0 +1,311 @@ +package main + +import ( + "bytes" + "encoding/binary" + "fmt" + "math" + "reflect" + "sync" + "testing" +) + +func missionOffersRequest() []byte { + // Original native QuestAlternative request: middle difficulty, neutral dimensions. + body := []byte{4, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0xda, 0xc1, 0xc0, 0, 0x0b, 0xb8, 0} + packet := n3Packet(0x5c436609, 50000, 1, body) + return packet[20:binary.BigEndian.Uint16(packet[6:8])] +} + +func TestMissionOffersRejectInvalidRequestsWithoutCharges(t *testing.T) { + for _, scenario := range []string{"short", "long", "version", "easy outside", "hard outside", "origin zero", "origin outside", "forged origin", + "seed", "offered quests", "wrong target type", "wrong subject type", "foreign subject", "unknown booth", "unsupported booth", + "far", "other playfield", "no cash", "one free slot", "dead", "loading", "not ready", "stale session", "legacy client"} { + t.Run(scenario, func(t *testing.T) { + world, output := newMissionOfferWorld(t) + player, client := world.characters[1], world.clients[1] + request, empty := missionOffersRequest(), false + switch scenario { + case "short": + request = request[:37] + case "long": + request = append(request, 0) + case "version": + request[16] = 3 + case "easy outside": + request[17] = 0 + case "hard outside": + request[17] = 12 + case "origin zero": + request[28] = 0 + case "origin outside": + request[28] = 9 + case "forged origin": + request[28], empty = 3, true + case "seed": + binary.BigEndian.PutUint32(request[24:28], 123) + case "offered quests": + request[37] = 1 + case "wrong target type": + binary.BigEndian.PutUint32(request[29:33], 56006) + case "wrong subject type": + binary.BigEndian.PutUint32(request[4:8], 56003) + case "foreign subject": + binary.BigEndian.PutUint32(request[8:12], 2) + case "unknown booth": + binary.BigEndian.PutUint32(request[33:37], 42) + empty = true + case "unsupported booth": + binary.BigEndian.PutUint32(request[33:37], 3221228509) + player.playfield, empty = 3037, true + case "far": + player.position[0], empty = 110, true + case "other playfield": + player.playfield, empty = 3037, true + case "no cash": + inventory := player.inventory + inventory.Credits = 0 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + empty = true + case "one free slot": + player.inventory.Items = make([]ownedItem, 29) + for index := range player.inventory.Items { + player.inventory.Items[index].Slot = uint32(64 + index) + } + empty = true + 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": + client.target = false + } + before, inventory := player.userData(), player.inventory + saved, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + + if err := world.handleMissionOffers(client, request); err != nil { + t.Fatal(err) + } + after, err := readTestItemStore(world) + + if err != nil || !bytes.Equal(saved, after) || !reflect.DeepEqual(before, player.userData()) || !reflect.DeepEqual(inventory, player.inventory) { + t.Fatalf("rejected generation changed saved or live state: %v", err) + } + if empty { + if len(output.packets) != 1 || binary.BigEndian.Uint16(output.packets[0][6:8]) != 51 || output.packets[0][50] != 0 { + t.Fatalf("rejected generation did not reset native selection: %x", output.packets) + } + } else if len(output.packets) != 0 { + t.Fatalf("malformed or stale request received an offer: %x", output.packets) + } + }) + } +} + +func TestMissionOfferSettingsRetainSignedDimensions(t *testing.T) { + for axis := 0; axis < 6; axis++ { + for _, value := range []int8{-101, -100, 100, 101} { + t.Run(fmt.Sprintf("%d/%d", axis, value), func(t *testing.T) { + world, output := newMissionOfferWorld(t) + request := missionOffersRequest() + request[18+axis] = byte(value) + + if err := world.handleMissionOffers(world.clients[1], request); err != nil { + t.Fatal(err) + } + + if value == -101 || value == 101 { + if len(output.packets) != 0 || world.characters[1].inventory.Credits != 5 { + t.Fatal("out-of-range dimension changed selection or wallet") + } + return + } + if len(output.packets) != 2 || !bytes.Equal(output.packets[1][31:37], request[18:24]) || world.characters[1].inventory.Credits != 4 { + t.Fatal("signed dimension was changed or generation was not charged") + } + }) + } + } +} + +func TestMissionOfferFailedFeePublishesNothingThenRetries(t *testing.T) { + for _, fault := range []struct{ name, statement string }{ + {"abort", "CREATE TRIGGER reject_mission_fee BEFORE UPDATE OF credits ON players BEGIN SELECT RAISE(ABORT, 'mission fee'); END"}, + {"ignored", "CREATE TRIGGER reject_mission_fee BEFORE UPDATE OF credits ON players BEGIN SELECT RAISE(IGNORE); END"}, + {"commit", "CREATE TABLE pending_mission_fee (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_mission_fee AFTER UPDATE OF credits ON players BEGIN INSERT INTO pending_mission_fee VALUES (999999); END"}, + } { + t.Run(fault.name, func(t *testing.T) { + world, output := newMissionOfferWorld(t) + before := world.characters[1].inventory + if _, err := world.db.Exec(fault.statement); err != nil { + t.Fatal(err) + } + + err := world.handleMissionOffers(world.clients[1], missionOffersRequest()) + restored := newTestInventoryServer(t).characters[1] + + if err == nil || len(output.packets) != 0 || !reflect.DeepEqual(before, world.characters[1].inventory) || !reflect.DeepEqual(before, restored.inventory) { + t.Fatal("failed generation fee was charged or published", err) + } + if _, err := world.db.Exec("DROP TRIGGER reject_mission_fee"); err != nil { + t.Fatal(err) + } + + err = world.handleMissionOffers(world.clients[1], missionOffersRequest()) + restored = newTestInventoryServer(t).characters[1] + + before.Credits = 4 + if err != nil || len(output.packets) != 2 || !reflect.DeepEqual(before, restored.inventory) || !reflect.DeepEqual(before, world.characters[1].inventory) { + t.Fatal("generation retry did not commit exactly one fee", err) + } + }) + } +} + +func TestMissionOfferDifficultyAndLevelCharge(t *testing.T) { + for _, test := range []struct { + level uint16 + difficulty byte + credits uint32 + }{ + {1, 1, 4}, {3, 11, 2}, {6, 6, 5}, + } { + t.Run(fmt.Sprintf("level%d/difficulty%d", test.level, test.difficulty), func(t *testing.T) { + world, output := newMissionOfferWorld(t) + world.characters[1].level = test.level + request := missionOffersRequest() + request[17] = test.difficulty + + if err := world.handleMissionOffers(world.clients[1], request); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t).characters[1] + + if restored.inventory.Credits != test.credits || world.characters[1].inventory.Credits != test.credits { + t.Fatal("generation fee does not match player level") + } + if test.level > 5 { + if len(output.packets) != 1 || output.packets[0][50] != 0 { + t.Fatal("unaffordable generation was not rejected") + } + return + } + if len(output.packets) != 2 || output.packets[1][30] != test.difficulty { + t.Fatal("valid difficulty setting was not preserved") + } + }) + } +} + +func TestMissionOfferConcurrentRequestsCannotOverdrawTheWallet(t *testing.T) { + world, output := newMissionOfferWorld(t) + inventory := world.characters[1].inventory + inventory.Credits = 1 + if err := world.saveInventory_locked(world.characters[1], inventory); err != nil { + t.Fatal(err) + } + var pending sync.WaitGroup + failures := make(chan error, 2) + + for range 2 { + pending.Add(1) + go func() { + defer pending.Done() + failures <- world.handleMissionOffers(world.clients[1], missionOffersRequest()) + }() + } + pending.Wait() + close(failures) + restored := newTestInventoryServer(t).characters[1] + + for err := range failures { + if err != nil { + t.Fatal(err) + } + } + if restored.inventory.Credits != 0 || world.characters[1].inventory.Credits != 0 || len(output.packets) != 3 || + binary.BigEndian.Uint32(output.packets[0][16:20]) != 0x2b333d6e || output.packets[1][50] != 1 || output.packets[2][50] != 0 { + t.Fatalf("concurrent generation did not produce one charged offer and one rejection: %x", output.packets) + } +} + +func newMissionOfferWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, output := newEquipmentWorld(t) + player := world.characters[1] + player.playfield, player.position = 3000, [3]float32{100, 115.75, 145} + inventory := player.inventory + inventory.Credits = 5 + if err := world.saveInventory_locked(player, inventory); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + output.packets = nil + return world, output +} + +func TestMissionOfferNativeSocketSeparatesBrowsingFromAcceptance(t *testing.T) { + newMissionOfferWorld(t) + world := newTestInventoryServer(t) + connection := connectZoningClient(t, world, true) + defer connection.Close() + before := world.characters[1].userData() + inventory := world.characters[1].inventory + request := missionOffersRequest() + + if _, err := connection.Write(targetPacket(n3Packet(0x5c436609, 50000, 1, request[16:]))); err != nil { + t.Fatal(err) + } + cash, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + offer, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t).characters[1] + + if len(cash) != 37 || binary.BigEndian.Uint32(cash[16:20]) != 0x2b333d6e || + binary.BigEndian.Uint32(cash[29:33]) != 61 || binary.BigEndian.Uint32(cash[33:37]) != 4 { + t.Fatalf("wrong committed generation charge: %x", cash) + } + inventory.Credits = 4 + if !reflect.DeepEqual(before, restored.userData()) || !reflect.DeepEqual(inventory, restored.inventory) { + t.Fatal("browsing changed something besides the saved generation fee") + } + if binary.BigEndian.Uint32(offer[16:20]) != 0x5c436609 || !bytes.Equal(offer[29:37], []byte{4, 6, 0, 0, 0, 0, 0, 0}) || + offer[41] != 5 || binary.BigEndian.Uint32(offer[42:46]) != 56001 || binary.BigEndian.Uint32(offer[46:50]) != 3221228472 || offer[50] != 1 || + binary.BigEndian.Uint32(offer[51:55]) != 56003 || binary.BigEndian.Uint32(offer[37:41]) == 0 || !bytes.Equal(offer[37:41], offer[55:59]) { + t.Fatalf("wrong offer identity or settings: %x", offer) + } + descriptionSize := int(binary.BigEndian.Uint32(offer[76:80])) + if binary.BigEndian.Uint32(offer[59:63]) != 14 || binary.BigEndian.Uint32(offer[71:75]) != 32 || + !bytes.HasPrefix(offer[80:80+descriptionSize], []byte("Recover the Blue Book of Secrets\n")) || offer[79+descriptionSize] != 0 { + t.Fatalf("invalid native Quest14 description: %x", offer) + } + reward := offer[80+descriptionSize:] + if binary.BigEndian.Uint32(reward[8:12]) != 5 || binary.BigEndian.Uint32(reward[12:16]) != 20 || binary.BigEndian.Uint32(reward[20:24]) != 100 { + t.Fatalf("wrong displayed cash/XP reward: %x", reward[:24]) + } + action := reward[80:216] + position := [3]float32{math.Float32frombits(binary.BigEndian.Uint32(action[124:128])), + math.Float32frombits(binary.BigEndian.Uint32(action[128:132])), math.Float32frombits(binary.BigEndian.Uint32(action[132:136]))} + if binary.BigEndian.Uint32(action[:4]) != 19 || binary.BigEndian.Uint32(action[4:8]) != 40822 || + binary.BigEndian.Uint32(action[108:112]) != 40016 || binary.BigEndian.Uint32(action[112:116]) != 3000 || + position != [3]float32{89.30216217041016, 115.14443969726562, 151.16087341308594} || + binary.BigEndian.Uint32(reward[216:220]) != 1009 || reward[len(reward)-1] != 0 { + t.Fatal("objective/location or empty unaccepted owner list was lost") + } +}