aorecomp

Anarchy Online classic in the browser

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


commit 5f9af110458aec2a9f41bf6d6b7574a3941f20ca
parent fd82a755c095e6146ccf2b0c97db380669d0eda2
Author: anon <anon@example.com>
Date:   Sat, 24 Oct 2026 06:13:21 +0000

Support atomic sales at native starter vending machines

Diffstat:
MTODO.md | 22+++++++++++++++++++---
Adocs/shops.md | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/insurance.go | 3+++
Mserver/inventory.go | 5+++++
Mserver/main.go | 15+++++++++++++++
Aserver/shops.go | 274+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/shops_test.go | 505+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mserver/state.go | 1+
Mserver/target_protocol.go | 8++++++++
9 files changed, 991 insertions(+), 3 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -400,11 +400,21 @@ checks are recorded in [treatment kits](docs/treatment-kit.md). space leaves both unchanged. Cover vending-machine types and access rules separately from NPC vendors, including reconnect and restart. - [ ] Browse one vendor's fixed stock. Check: the native shop window displays - the expected items, QLs and prices without transferring ownership. + the expected items, QLs and prices without transferring ownership. Recover + the starter QETS category's actual membership; original descriptors identify + the category but do not establish its stock. Do not infer stock from names. - [ ] Buy one item. Check: credits and inventory change together; insufficient credits or space leaves both unchanged. -- [ ] Sell one inventory item. Check: ownership and credits change once and - repeating the request cannot sell the same item twice. +- [x] Sell one inventory item. Check: ownership and credits change once and + repeating the request cannot sell the same item twice. The original Omni + and Clan starter terminals support atomic sales, native offers, removal, + cancellation and confirmation; see [vending-machine sales](docs/shops.md). +- [ ] Expand native shop transaction testing beyond one-item sales. Check: + charged and partially used stacks, zero-value items, multiple offers, + removal/re-addition, NoDrop and backpack contents; displayed versus awarded + prices at Computer Literacy boundaries; mixed purchase/sale baskets, lost + replies and reconnect/restart. Keep every owned item and credit accounted + for on both successful and rejected paths. - [ ] Refresh one vendor's stock. Check: the intended stock policy updates the list without changing an already purchased item's identity or properties. @@ -753,6 +763,12 @@ current SQLite storage when applying these findings. ## Thorough gameplay regression testing +- [ ] Reproduce and fix a WASM freeze during live control-panel player edits + that reload the playfield. Check: capture the full stack for the observed + `ErrorEvent: unwind`, verify that native frames and world traffic resume, + and repeat edits and zoning without requiring a page reload. Shop testing + saw frozen frames with `ABORT` false; the cause is not yet established. + These checks are additional work, not claims that the existing feature tests already establish complete gameplay correctness. Cover positive and negative cases through native controls, with automation where practical. Compare server diff --git a/docs/shops.md b/docs/shops.md @@ -0,0 +1,161 @@ +# Starter vending-machine sales + +The original Omni and Clan training-ground vending machines accept staged +sales from ordinary inventory. An offer remains owned by the player until +Accept commits its removal and the credit award in one SQLite transaction. +Cancel and removing an offer restore the same item. Purchase catalogs and +stock rotation remain unresolved and are not supplied by this implementation. + +## Original placements and access + +Resource type 1000026 contains these shipped placements: + +| Machine identity | Playfield | Position | Template | Sell modifier 426 | +| --- | --- | --- | --- | --- | +| 51035:0xc00003b6 | 950 | 60, 13.999998, 50 | 100035 | 5 | +| 51035:0xc00003b8 | 952 | 48, 13.999998, 62 | 100034 | 4 | + +The templates' Use action requires Omni and Clan affiliation respectively. +The server checks that authored requirement, a living authenticated current +session, world readiness, no pending equipment change, and five-metre distance +in the same playfield. Five metres is a provisional server policy; the original +client's player-trade distance does not prove the historical vending distance. + +Native scene picking can send Use for static identity type 51005 with the +same instance ID. That request resolves to the supported placement and receives +the same validation. Trade messages identify the machine as type 51035. + +`local/shop-research/catalog.json` retains parsed templates, raw placement +bytes and hashes. The Omni placement record SHA-256 is +`43ada4f7f2ee7d507b45888758ea61e1e90277656e23c1bdd4af30fe6c5ea9a5`. +Both starter templates name stock category QETS. A bounded scan of all 278644 +resource payloads found category descriptors but no authoritative membership +list. See `local/shop-research/stock/README.md`; starter-looking item names +are insufficient evidence for a purchase catalog. + +## Native handshake and inventory references + +The target is `anarchy-vanilla-14.9.1/kkr.dll`, SHA-256 +`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`. +The UI target `ddr.dll` SHA-256 is +`3c937161de8f690351c3c08e158431417cee9ced77a41b677e7123b61a8c9883`. +Addresses below use the original image base 0x10000000. + +VendingMachineFullUpdate, key 0x7f544905, creates the machine using inherited +SimpleItem marker 11, Lockable marker 2 and Chest marker 3. Its world quaternion +is XYZW, so the placement's identity quaternion is sent as 0,0,0,1. Template +stat 23 and quality stat 701 select the authored appearance and behavior. + +After successful GenericCmd Use, initialize two distinct native state objects: + +1. Machine-subject Trade action 0, A=player, B=zero, creates the machine's + per-player transaction record through KKR 0x100a9cf0. +2. Player-subject Trade action 0, A=machine, B=machine, opens shop mode. + DDR TradeViewModule startup 0x100485b0 uses B as catalog owner. A zero B + selects ordinary player trading and omits the shop sale-credit display. + +TradeIIR key 0x36284f6e has six body words: version 1, action, A.type, A.id, +B.type and B.id. Player sale Add action 4 uses A=player and B=(104,inventory +slot). Native ordinary inventory slots 48..77 translate to shared slots +64..93. The reply moves the item into native TradeInv and emits the existing +TradeUpdated notification. Remove action 5 uses B=(108,trade slot); page 111 +belongs to machine stock. Basket slots remain stable when another is removed. + +Player Abort action 2 restores native offered items and clears the machine's +record. The native Accept button first sends SetCash action 6 with zero cash, +then Accept action 1. The server echoes that zero reset without changing +credits; a nonzero cash offer is rejected. Complete action 3 invokes the +vending finalizer 0x100a99d0. That +function consumes offered items but does not credit player cash, so the server +sends the authoritative absolute cash stat 61 after completion. + +An empty ShopUpdate would print the original "contact a GM" warning. No stock +update is sent while the purchase catalog is unresolved. Native empty catalog +and purchase-basket lists still permit sale offers. + +Evidence is retained under `local/shop-research/wire/`. Key records: + +| Observation | Evidence | +| --- | --- | +| Packet registrations | ev_26009c7c7f943a6942cbffd43a260613f1ef722f51d073d62248e83f64600c95 | +| Native serialization | ev_5fe35f4305fb3b2ec2b32dd82476cb8f06a0e6e886698554938a898003b9f24b | +| Shop UI mode and price refresh | ev_f5717956dbc1f446ae83949a01f62f1535d4e2f743295d46fb199db6490f039e | +| Trade-start UI receiver | ev_1f9fdd961d7afda27c01e108a5821b696d81f3110667a7078b29988ec7ae0e19 | + +## Pricing and commit rules + +Prices use original item stat 74, including its special quality curve. The +rounded linear interpolation is followed by `min + (value-min)^2/(max-min)`; +equal endpoints and exact endpoint values are unchanged. Ordinary item price +reader 0x100f0c80 and shop price reader 0x100aa630 use that same curve. + +The accepted-transfer calculation in KKR 0x100a99d0 is the chosen server +policy. It is client evidence, not a recovered historical server algorithm. +Let T truncate toward zero, U be float32(item price), N the offered count, +S the terminal's authored sell modifier and CL effective Computer Literacy: + +``` +if type != 51018 and maximum charges > 0: + U = float32(U / maximum charges) +base = T(N * U * S * binary64(0.01)) +markup = T(CL * float32(0.025)) +sale = base + T(markup * float32(0.01) * base) +``` + +The float32 constants and truncation boundaries matter. Accepted-transfer +pricing has no observed CL cap. The UI staging calculation 0x100a9e20 rounds +the CL addition per unit before applying count and modifier, so some boundary +values can differ from accepted-transfer pricing by a credit. Preserve this +distinction when adding purchases or investigating displayed quote rounding. +See `local/shop-research/pricing/findings.md` and its retained REA evidence. + +NoDrop flag 0x04000000 rejects a sale. Dynamic items require absent/default +TimeExist or explicit stat 8 equal to -1. Backpacks are currently rejected; +selling their contents and container policy remain separate work. + +The server snapshots each offered owned item and revalidates it on Accept. +Changed ownership, slot, quantity or item properties abort the draft, as do +lost proximity, affiliation, life or readiness. Ordinary inventory actions +cancel the draft before proceeding, so an offered item cannot also disappear +into an equipment change. Credit overflow rejects the whole transaction. + +The draft stays in memory. Accept removes item records and awards credits +through the existing atomic inventory save before publishing Complete. Failed +SQLite writes leave both RAM and disk unchanged. A lost completion reply or +repeated/concurrent Accept cannot award the sale twice. Reconnect discards an +unaccepted draft and reloads authoritative inventory and credits. + +## Verification + +`server/shops_test.go` exercises native socket Use and sale dispatch, price +curves, charges, CL boundaries, stable basket slots, cancellation, stale item +snapshots, NoDrop, backpacks, forged identities/actions, session replacement, +faction/range/life checks, overflow, concurrent Accept, lost replies, SQLite +write failures and equipping an offered item. Database reopen checks verify +ownership and credits together. + +The published WASM client was exercised in headed Chromium on the GPU. +The native terminal click sent static identity 51005:0xc00003b6; the reply +created the machine record and opened shop mode with the correct catalog +identity. Owned Kinetic Axe instance 202 appeared in the sale basket with a +605-credit quote. Removal restored that same native item; cancelling a filled +offer restored it with cash still 100, and the terminal reopened in the same +session. SQLite retained ownership throughout these drafts. + +Accept sent the captured zero-cash reset followed by confirmation. Native cash +became 705, the item left both native inventory and SQLite, and a fresh WASM +connection retained 705 with an empty inventory. There were no page errors in +the completed scenario. `local/shop-research/runtime/verification.json` records +the assertions, matched trade messages and test-owned identities; step PNGs, +native memory snapshots and raw WebSocket frames are retained beside it. + +The dummy-HDMI display's power-saving state had limited animation to roughly +one frame per second during early input attempts. The completed scenario kept +that display awake, and pointer hover preceded clicks so native hit testing +settled before button input. The display setting was restored after testing. +No WASM source or build change was needed for this sale milestone. + +Final checks passed: `go test ./server/...` (342 seconds), focused +`go test -race ./server -run '^TestShop' -count=1` (144 seconds), and +`go vet -stdversion=false ./server/...`. The disabled analyzer covers the +existing Go1.24 declaration versus WaitGroup.Go toolchain mismatch. diff --git a/server/insurance.go b/server/insurance.go @@ -6,6 +6,9 @@ import ( ) func (server *server) handleTerminalUse(client *worldClient, body []byte) error { + if _, shop := starterShop(binary.BigEndian.Uint32(body[44:48])); shop && binary.BigEndian.Uint32(body[40:44]) == 51005 { + return server.handleShopUse(client, body) + } server.updateMutex.Lock() defer server.updateMutex.Unlock() server.mutex.Lock() diff --git a/server/inventory.go b/server/inventory.go @@ -187,6 +187,11 @@ func (server *server) handleInventory(client *worldClient, body []byte) error { binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id { return nil } + if client.shop != nil { + if err := server.abortShop_locked(client); err != nil { + return err + } + } if key == 0x5e477770 && binary.BigEndian.Uint32(body[20:24]) == 107 && binary.BigEndian.Uint32(body[24:28])>>16 != 0 { return server.handleBackpackAction_locked(client, body) } diff --git a/server/main.go b/server/main.go @@ -347,6 +347,7 @@ func (server *server) serveWorldClient(client *worldClient) error { client.id = character.id client.npcs = make(map[uint32]bool) client.lootCorpse = 0 + client.shop = nil updates := [][]byte{playfieldPacket(character), characterPacket(character)} for id, other := range server.characters { if id != character.id && other.playfield == character.playfield && server.clients[id] != nil { @@ -378,6 +379,14 @@ func (server *server) serveWorldClient(client *worldClient) error { } } updates = append(updates, server.combatInterest_locked(client, nil)...) + if client.target { + for _, id := range []uint32{0xc00003b6, 0xc00003b8} { + machine, _ := starterShop(id) + if machine.playfield == character.playfield { + updates = append(updates, shopMachinePacket(machine)) + } + } + } updates = append(updates, gameTimePacket(character.id, server.gameSeconds_locked())) spawn := characterPacket(character) playfield := character.playfield @@ -451,6 +460,10 @@ func (server *server) serveWorldClient(client *worldClient) error { decodeInventory1491(body) } switch binary.BigEndian.Uint32(body[0:4]) { + case 0x36284f6e: + if err := server.handleShopTrade(client, body); err != nil { + return err + } case 0x51492120: if err := server.handleFlingShot(client, body); err != nil { return err @@ -469,6 +482,8 @@ func (server *server) serveWorldClient(client *worldClient) error { err = server.handleReload(client, body) } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 102 || binary.BigEndian.Uint32(body[40:44]) == 104 || binary.BigEndian.Uint32(body[40:44]) == 51017) { err = server.handleOwnedItemUse(client, body) + } else if len(body) == 48 && binary.BigEndian.Uint32(body[40:44]) == 51035 { + err = server.handleShopUse(client, body) } else if len(body) == 48 && (binary.BigEndian.Uint32(body[40:44]) == 51005 || binary.BigEndian.Uint32(body[40:44]) == 51059) { err = server.handleTerminalUse(client, body) } else { diff --git a/server/shops.go b/server/shops.go @@ -0,0 +1,274 @@ +package main + +import ( + "ao/server/gamedata" + "encoding/binary" + "fmt" + "math" + "slices" + "time" +) + +type shopMachine struct { + id uint32 + template uint32 + playfield uint32 + position [3]float32 +} + +type shopTrade struct { + machine shopMachine + items map[uint32]ownedItem +} + +func starterShop(id uint32) (shopMachine, bool) { + // Original type 1000026 statels in the Omni and Clan training grounds. + switch id { + case 0xc00003b6: + return shopMachine{id, 100035, 950, [3]float32{60, 13.999998, 50}}, true + case 0xc00003b8: + return shopMachine{id, 100034, 952, [3]float32{48, 13.999998, 62}}, true + } + return shopMachine{}, false +} + +func (server *server) canUseShop_locked(client *worldClient, machine shopMachine) bool { + player := server.characters[client.id] + if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || + client.equipment != nil || player.playfield != machine.playfield { + return false + } + position := predictedPosition_locked(player, client, time.Now()) + x, y, z := position[0]-machine.position[0], position[1]-machine.position[1], position[2]-machine.position[2] + if x*x+y*y+z*z > 5*5 { + return false + } + // These two templates author a single faction equality on their Use action. + for _, section := range gamedata.ItemTemplates[machine.template].Sections { + if section.Actions == nil { + continue + } + for _, action := range *section.Actions { + if action.Type != 3 { + continue + } + for _, requirement := range action.Requirements { + if requirement.Stat != 33 || requirement.Operator != 0 || uint32(player.appearance>>9&3) != uint32(requirement.Value) { + return false + } + } + return true + } + } + return false +} + +func shopMachinePacket(machine shopMachine) []byte { + // VendingMachineFullUpdate inherits SimpleItem 11, Lockable 2 and Chest 3. + var body []byte + for _, value := range []uint32{11, 0, 0} { + body = binary.BigEndian.AppendUint32(body, value) + } + for _, value := range machine.position { + body = binary.BigEndian.AppendUint32(body, math.Float32bits(value)) + } + for _, value := range []uint32{0, 0, 0, math.Float32bits(1), machine.playfield, 0, 0} { + body = binary.BigEndian.AppendUint32(body, value) + } + body = append(body, 0, 0) + body = binary.BigEndian.AppendUint32(body, 3*1009) + for _, value := range []uint32{23, machine.template, 701, 1, 0, 2, 0, 1009, 3} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x7f544905, 51035, machine.id, body) +} + +func shopTradePacket(subject [2]uint32, action uint32, first, second [2]uint32) []byte { + var body []byte + for _, value := range []uint32{1, action, first[0], first[1], second[0], second[1]} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x36284f6e, subject[0], subject[1], body) +} + +func (server *server) handleShopUse(client *worldClient, body []byte) error { + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + defer server.mutex.Unlock() + if len(body) != 48 { + return fmt.Errorf("invalid shop use length") + } + if binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || + binary.BigEndian.Uint32(body[16:20]) != 0 || binary.BigEndian.Uint32(body[24:28]) != 3 || + binary.BigEndian.Uint32(body[28:32]) != 1 || binary.BigEndian.Uint32(body[32:36]) != 50000 || + binary.BigEndian.Uint32(body[36:40]) != client.id || + (binary.BigEndian.Uint32(body[40:44]) != 51035 && binary.BigEndian.Uint32(body[40:44]) != 51005) || + !client.target || server.clients[client.id] != client || !client.ready || client.loading { + return nil + } + sequence := binary.BigEndian.Uint32(body[20:24]) + if sequence <= client.useSequence { + return nil + } + client.useSequence = sequence + machine, exists := starterShop(binary.BigEndian.Uint32(body[44:48])) + accepted := exists && server.canUseShop_locked(client, machine) + reply := append([]byte(nil), body[16:]...) + binary.BigEndian.PutUint32(reply, 2) + if accepted { + binary.BigEndian.PutUint32(reply, 1) + } + if err := client.send(n3Packet(0x52526858, 50000, client.id, reply)); err != nil || !accepted { + return err + } + if client.shop != nil { + if err := server.abortShop_locked(client); err != nil { + return err + } + } + client.shop = &shopTrade{machine: machine, items: make(map[uint32]ownedItem)} + if err := client.send(shopMachinePacket(machine)); err != nil { + return err + } + // Create the machine's per-player trade record before the GUI queries it. + if err := client.send(shopTradePacket([2]uint32{51035, machine.id}, 0, [2]uint32{50000, client.id}, [2]uint32{})); err != nil { + return err + } + // DDR TradeViewModule uses the second identity as the shop catalog and mode. + // Stock category QETS is unresolved; no fabricated purchase catalog is sent. + return client.send(shopTradePacket([2]uint32{50000, client.id}, 0, [2]uint32{51035, machine.id}, [2]uint32{51035, machine.id})) +} + +func (server *server) abortShop_locked(client *worldClient) error { + client.shop = nil + return client.send(shopTradePacket([2]uint32{50000, client.id}, 2, [2]uint32{}, [2]uint32{})) +} + +func (item ownedItem) shopPrice() uint32 { + low, high := item.templateIDs() + first, second := gamedata.ItemTemplates[low], gamedata.ItemTemplates[high] + if low == high { + return itemStat(first, 74) + } + // kkr.dll FUN_100aa630 and FUN_100f1320 curve stat74 after interpolation. + price := interpolateItemValue(int32(itemStat(first, 74)), int32(itemStat(second, 74)), *first.Quality, *second.Quality, item.Quality) + minimum, maximum := min(itemStat(first, 74), itemStat(second, 74)), max(itemStat(first, 74), itemStat(second, 74)) + if minimum == maximum || uint32(price) == minimum || uint32(price) == maximum { + return uint32(price) + } + difference := float64(price) - float64(minimum) + return uint32(float64(minimum) + difference*difference/float64(maximum-minimum)) +} + +func shopSalePrice(item ownedItem, modifier, computerLiteracy uint32) uint64 { + // kkr.dll FUN_100a99d0 rounds the charge-normalized unit price to float32. + price := float32(item.shopPrice()) + if charges := int32(itemStat(item.templateDefinition(), 212)); item.Type != 51018 && charges > 0 { + price /= float32(charges) + } + base := uint64(float64(item.Count) * float64(price) * float64(modifier) * 0.01) + markup := uint64(float64(computerLiteracy) * float64(float32(0.025))) + return base + uint64(float64(markup)*float64(float32(0.01))*float64(base)) +} + +func (server *server) handleShopTrade(client *worldClient, body []byte) error { + if len(body) != 40 { + return fmt.Errorf("invalid trade length") + } + server.updateMutex.Lock() + defer server.updateMutex.Unlock() + server.mutex.Lock() + defer server.mutex.Unlock() + if !client.target || server.clients[client.id] != client || !client.ready || client.loading || client.shop == nil || + binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || binary.BigEndian.Uint32(body[16:20]) != 1 { + return nil + } + action := binary.BigEndian.Uint32(body[20:24]) + if action == 2 || !server.canUseShop_locked(client, client.shop.machine) { + return server.abortShop_locked(client) + } + player := server.characters[client.id] + first := [2]uint32{binary.BigEndian.Uint32(body[24:28]), binary.BigEndian.Uint32(body[28:32])} + second := [2]uint32{binary.BigEndian.Uint32(body[32:36]), binary.BigEndian.Uint32(body[36:40])} + switch action { + case 4: + if first != [2]uint32{50000, client.id} || second[0] != 104 || second[1] < 64 || second[1] >= 94 { + return server.abortShop_locked(client) + } + index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == second[1] }) + if index < 0 { + return server.abortShop_locked(client) + } + item := player.inventory.Items[index] + definition := item.templateDefinition() + if itemStat(definition, 0)&0x04000000 != 0 || item.Type == 51017 { + return server.abortShop_locked(client) + } + for _, stat := range definition.Stats { + if item.Type == 51022 && stat[0] == 8 && int32(stat[1]) != -1 { + return server.abortShop_locked(client) + } + } + for _, other := range client.shop.items { + if other.ID == item.ID { + return nil + } + } + // The native trade inventory keeps stable slots when an offer is removed. + var slot uint32 + for { + if _, occupied := client.shop.items[slot]; !occupied { + break + } + slot++ + } + client.shop.items[slot] = item + return client.send(shopTradePacket([2]uint32{50000, client.id}, action, first, second)) + case 5: + if _, exists := client.shop.items[second[1]]; first != [2]uint32{50000, client.id} || second[0] != 108 || !exists { + return server.abortShop_locked(client) + } + delete(client.shop.items, second[1]) + return client.send(shopTradePacket([2]uint32{50000, client.id}, action, first, second)) + case 1, 6: + if first != [2]uint32{} || second != [2]uint32{} { + return server.abortShop_locked(client) + } + // The native shop Accept button clears its cash offer before confirming. + if action == 6 { + return client.send(shopTradePacket([2]uint32{50000, client.id}, 6, first, second)) + } + inventory := player.inventory + inventory.Items = slices.Clone(inventory.Items) + literacy := player.effectiveSkill(161, player.stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0}) + modifier := itemStat(gamedata.ItemTemplates[client.shop.machine.template], 426) + var credits uint64 + for _, item := range client.shop.items { + index := slices.Index(inventory.Items, item) + if index < 0 { + return server.abortShop_locked(client) + } + credits += shopSalePrice(item, modifier, literacy) + inventory.Items = slices.Delete(inventory.Items, index, index+1) + } + if credits > uint64(1000000000-inventory.Credits) { + return server.abortShop_locked(client) + } + inventory.Credits += uint32(credits) + // Ownership removal and the credit award share the existing SQLite transaction. + if len(client.shop.items) != 0 { + if err := server.saveInventory_locked(player, inventory); err != nil { + return err + } + } + client.shop = nil + if err := client.send(shopTradePacket([2]uint32{50000, client.id}, 3, [2]uint32{}, [2]uint32{})); err != nil { + return err + } + stats := binary.BigEndian.AppendUint32(nil, 61) + stats = binary.BigEndian.AppendUint32(stats, inventory.Credits) + return client.send(n3Packet(0x2b333d6e, 50000, client.id, stats)) + } + return server.abortShop_locked(client) +} diff --git a/server/shops_test.go b/server/shops_test.go @@ -0,0 +1,505 @@ +package main + +import ( + "ao/server/gamedata" + "bytes" + "encoding/binary" + "fmt" + "reflect" + "sync" + "testing" +) + +func TestShopSalePricesUseNativeQualityChargesAndLiteracyRounding(t *testing.T) { + for _, scenario := range []struct { + template uint32 + quality uint32 + count uint16 + literacy uint16 + credits uint32 + }{ + {209283, 1, 1, 39, 605}, + {209283, 1, 1, 40, 611}, + {209283, 1, 1, 80, 617}, + {209283, 1, 1, 4000, 1209}, + {43552, 1, 1, 40, 25}, + {25812, 1, 50, 40, 7}, + {25812, 1, 1, 40, 0}, + {25812, 1, 49, 40, 7}, + {85366, 1, 25, 40, 1}, + {21605, 1, 100, 40, 1}, + {85512, 1, 1, 40, 31}, + {85512, 2, 1, 40, 32}, + {85512, 100, 1, 40, 7457}, + {85512, 101, 1, 40, 7608}, + {85512, 199, 1, 40, 29737}, + {85511, 200, 1, 40, 30038}, + } { + t.Run(fmt.Sprintf("%d/QL%d/CL%d", scenario.template, scenario.quality, scenario.literacy), func(t *testing.T) { + world, _ := newShopWorld(t) + player, client := world.characters[1], world.clients[1] + player.stats.Abilities.Intelligence = 5 + player.stats.TradeRepair.ComputerLiteracy = scenario.literacy - 1 + player.inventory.Items[0] = ownedItem{ID: 1, Type: gamedata.ItemTemplates[scenario.template].HeaderWords[0], Template: scenario.template, Quality: scenario.quality, Slot: 64, Count: scenario.count} + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + + if player.inventory.Credits != 100+scenario.credits || len(player.inventory.Items) != 0 { + t.Fatalf("sale credited %d, want %d", player.inventory.Credits-100, scenario.credits) + } + }) + } +} + +func shopUseRequest(sequence uint32) []byte { + var body []byte + for _, value := range []uint32{0, sequence, 3, 1, 50000, 1, 51035, 0xc00003b6} { + body = binary.BigEndian.AppendUint32(body, value) + } + return n3Packet(0x52526858, 50000, 1, body)[20:] +} + +func newShopWorld(t *testing.T) (*server, *combatTestConn) { + t.Helper() + world, conn := newEquipmentWorld(t) + player := world.characters[1] + player.position, player.appearance = [3]float32{60, 14.75, 53}, 0x515 + player.inventory.Credits = 100 + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + if err := world.handleShopUse(world.clients[1], shopUseRequest(1)); err != nil { + t.Fatal(err) + } + conn.packets = nil + return world, conn +} + +func TestShopNativeSocketUseAndSale(t *testing.T) { + newShopWorld(t) + world := newTestInventoryServer(t) + connection := connectZoningClient(t, world, true) + defer connection.Close() + + request := shopUseRequest(1) + binary.BigEndian.PutUint32(request[40:44], 51005) + connection.Write(targetPacket(n3Packet(0x52526858, 50000, 1, request[16:]))) + for index, key := range []uint32{0x52526858, 0x7f544905, 0x36284f6e, 0x36284f6e} { + packet, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + if binary.BigEndian.Uint32(packet[16:20]) != key { + t.Fatalf("native shop opening sent %x, want key %x", packet, key) + } + if key == 0x52526858 && binary.BigEndian.Uint32(packet[29:33]) != 1 { + t.Fatalf("native shop use was rejected: %x", packet) + } + if index == 2 && (binary.BigEndian.Uint32(packet[20:24]) != 51035 || binary.BigEndian.Uint32(packet[24:28]) != 0xc00003b6 || + binary.BigEndian.Uint32(packet[37:41]) != 50000 || binary.BigEndian.Uint32(packet[41:45]) != 1) { + t.Fatalf("machine trade record was not initialized before the window: %x", packet) + } + if index == 3 && (binary.BigEndian.Uint32(packet[20:24]) != 50000 || binary.BigEndian.Uint32(packet[24:28]) != 1 || + binary.BigEndian.Uint32(packet[37:41]) != 51035 || binary.BigEndian.Uint32(packet[41:45]) != 0xc00003b6 || + binary.BigEndian.Uint32(packet[45:49]) != 51035 || binary.BigEndian.Uint32(packet[49:53]) != 0xc00003b6) { + t.Fatalf("player trade window has the wrong partner: %x", packet) + } + } + connection.Write(targetPacket(shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64}))) + if _, err := readPacket(connection); err != nil { + t.Fatal(err) + } + connection.Write(targetPacket(shopTradePacket([2]uint32{50000, 1}, 6, [2]uint32{}, [2]uint32{}))) + reset, err := readPacket(connection) + if err != nil || binary.BigEndian.Uint32(reset[33:37]) != 6 { + t.Fatalf("native zero-cash reset aborted the shop: %x %v", reset, err) + } + connection.Write(targetPacket(shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{}))) + complete, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + cash, err := readPacket(connection) + if err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t) + + if binary.BigEndian.Uint32(complete[16:20]) != 0x36284f6e || binary.BigEndian.Uint32(complete[33:37]) != 3 || + binary.BigEndian.Uint32(cash[16:20]) != 0x2b333d6e || binary.BigEndian.Uint32(cash[33:37]) != 705 || + restored.characters[1].inventory.Credits != 705 || len(restored.characters[1].inventory.Items) != 0 { + t.Fatalf("native socket sale did not commit before acknowledgement: complete=%x cash=%x", complete, cash) + } +} + +func TestShopInvalidOffersLeaveCashAndInventoryUnchanged(t *testing.T) { + for _, scenario := range []string{"NoDrop", "backpack", "foreign owner", "equipped", "wrong page", "missing item", "purchase", "cash offer", "unsolicited complete", "wrong version", "wrong subject"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newShopWorld(t) + client, player := world.clients[1], world.characters[1] + body := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:] + switch scenario { + case "NoDrop": + player.inventory.Items[0] = ownedItem{ID: 1, Type: 51018, Template: 121567, Quality: 1, Slot: 64, Count: 1} + case "backpack": + player.inventory.Items[0] = ownedItem{ID: 1, Type: 51017, Template: 99228, Quality: 1, Slot: 64, Count: 1} + case "foreign owner": + binary.BigEndian.PutUint32(body[28:32], 2) + case "equipped": + binary.BigEndian.PutUint32(body[36:40], 6) + case "wrong page": + binary.BigEndian.PutUint32(body[32:36], 102) + case "missing item": + binary.BigEndian.PutUint32(body[36:40], 65) + case "purchase": + binary.BigEndian.PutUint32(body[24:28], 51035) + binary.BigEndian.PutUint32(body[28:32], 0xc00003b6) + binary.BigEndian.PutUint32(body[32:36], 111) + case "cash offer": + binary.BigEndian.PutUint32(body[20:24], 6) + binary.BigEndian.PutUint32(body[24:28], 0) + binary.BigEndian.PutUint32(body[28:32], 1) + binary.BigEndian.PutUint32(body[32:36], 0) + binary.BigEndian.PutUint32(body[36:40], 0) + case "unsolicited complete": + binary.BigEndian.PutUint32(body[20:24], 3) + case "wrong version": + binary.BigEndian.PutUint32(body[16:20], 2) + case "wrong subject": + binary.BigEndian.PutUint32(body[8:12], 2) + } + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + + err = world.handleShopTrade(client, body) + after, readErr := readTestItemStore(world) + + if err != nil || readErr != nil || !bytes.Equal(before, after) || client.shop != nil && len(client.shop.items) != 0 { + t.Fatal("invalid offer changed ownership, credits or basket") + } + }) + } +} + +func TestShopNativeSalePersistsAndCannotBeReplayed(t *testing.T) { + world, conn := newShopWorld(t) + client := world.clients[1] + add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:] + accept := shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:] + + if err := world.handleShopTrade(client, add); err != nil { + t.Fatal(err) + } + world.handleShopTrade(client, add) + staged := newTestInventoryServer(t).characters[1].inventory + if err := world.handleShopTrade(client, accept); err != nil { + t.Fatal(err) + } + world.handleShopTrade(client, accept) + world.handleShopTrade(client, add) + restored := newTestInventoryServer(t) + + if staged.Credits != 100 || len(staged.Items) != 1 { + t.Fatal("staging changed durable ownership or cash") + } + if restored.characters[1].inventory.Credits != 705 || len(restored.characters[1].inventory.Items) != 0 || len(restored.items) != 0 || + world.characters[1].inventory.Credits != 705 || client.shop != nil { + t.Fatal("sale did not remove exactly one item and award 605 credits once") + } + if len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[1][33:37]) != 3 || + binary.BigEndian.Uint32(conn.packets[2][29:33]) != 61 || binary.BigEndian.Uint32(conn.packets[2][33:37]) != 705 { + t.Fatalf("wrong native sale acknowledgement or absolute credit update: %x", conn.packets) + } +} + +func TestShopCancelAndRemovePreserveTheOwnedItem(t *testing.T) { + for _, action := range []uint32{2, 5} { + t.Run(fmt.Sprint(action), func(t *testing.T) { + world, conn := newShopWorld(t) + client := world.clients[1] + before := world.characters[1].inventory + world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]) + + first, second := [2]uint32{}, [2]uint32{} + if action == 5 { + first, second = [2]uint32{50000, 1}, [2]uint32{108, 0} + } + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, action, first, second)[20:]); err != nil { + t.Fatal(err) + } + if action == 5 { + world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]) + } + restored := newTestInventoryServer(t).characters[1].inventory + + if before.Credits != restored.Credits || !reflect.DeepEqual(before.Items, restored.Items) || !reflect.DeepEqual(before, world.characters[1].inventory) || client.shop != nil || len(conn.packets) < 2 { + t.Fatal("cancelled or removed offer changed ownership or credits") + } + }) + } +} + +func TestShopRemovingAnOfferKeepsTheOtherTradeSlotsStable(t *testing.T) { + world, _ := newShopWorld(t) + client := world.clients[1] + if granted, err := world.grantItem_locked(world.characters[1], 43552); err != nil || !granted { + t.Fatalf("grant clinic: %v %v", granted, err) + } + if granted, err := world.grantItem_locked(world.characters[1], 43552); err != nil || !granted { + t.Fatalf("grant second clinic: %v %v", granted, err) + } + for _, slot := range []uint32{64, 65, 66} { + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, slot})[20:]); err != nil { + t.Fatal(err) + } + } + + for _, slot := range []uint32{0, 2} { + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{50000, 1}, [2]uint32{108, slot})[20:]); err != nil { + t.Fatal(err) + } + } + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t).characters[1].inventory + + if restored.Credits != 125 || !reflect.DeepEqual(restored.Items, []ownedItem{ + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1}, + {ID: 3, Type: 51005, Template: 43552, Quality: 1, Slot: 66, Count: 1}, + }) { + t.Fatal("removing offers shifted the remaining trade slot or sold the wrong item") + } +} + +func TestShopLostCompletionReplyDoesNotReplayTheSale(t *testing.T) { + world, _ := newShopWorld(t) + client := world.clients[1] + world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]) + client.conn = &failingCombatConn{} + accept := shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:] + + err := world.handleShopTrade(client, accept) + world.handleShopTrade(client, accept) + restored := newTestInventoryServer(t).characters[1].inventory + + if err == nil || restored.Credits != 705 || len(restored.Items) != 0 || client.shop != nil { + t.Fatal("lost acknowledgement lost or duplicated a committed sale") + } +} + +func TestShopConcurrentAcceptAwardsCreditsOnce(t *testing.T) { + world, _ := newShopWorld(t) + client := world.clients[1] + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]); err != nil { + t.Fatal(err) + } + accept := shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:] + errors := make(chan error, 2) + var requests sync.WaitGroup + + for range 2 { + requests.Go(func() { errors <- world.handleShopTrade(client, accept) }) + } + requests.Wait() + close(errors) + for err := range errors { + if err != nil { + t.Fatal(err) + } + } + restored := newTestInventoryServer(t).characters[1].inventory + + if restored.Credits != 705 || len(restored.Items) != 0 { + t.Fatal("concurrent accept duplicated or lost the sale") + } +} + +func TestShopClanTerminalUsesItsAuthoredSaleModifier(t *testing.T) { + world, _ := newShopWorld(t) + player, client := world.characters[1], world.clients[1] + player.appearance, player.playfield, player.position = 0x315, 952, [3]float32{48, 14, 65} + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + request := shopUseRequest(2) + binary.BigEndian.PutUint32(request[44:48], 0xc00003b8) + + if err := world.handleShopUse(client, request); err != nil { + t.Fatal(err) + } + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]); err != nil { + t.Fatal(err) + } + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t).characters[1].inventory + + if restored.Credits != 584 || len(restored.Items) != 0 { + t.Fatal("Clan terminal did not award its authored four-percent sale price") + } +} + +func TestShopEquippingAnOfferedItemCancelsTheSale(t *testing.T) { + world, conn := newShopWorld(t) + client := world.clients[1] + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]); err != nil { + t.Fatal(err) + } + conn.packets = nil + + if err := world.handleInventory(client, inventoryMovePacket(1, 64, 6)[20:]); err != nil { + t.Fatal(err) + } + if client.equipment == nil { + t.Fatal("equip did not start after cancelling the offer") + } + world.advanceEquipment(client.equipment.readyAt) + if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil { + t.Fatal(err) + } + restored := newTestInventoryServer(t).characters[1].inventory + + if client.shop != nil || restored.Credits != 100 || !reflect.DeepEqual(restored.Items, []ownedItem{ + {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 6, Count: 1}, + }) { + t.Fatal("offered equipment disappeared or was also sold") + } + if len(conn.packets) == 0 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x36284f6e || binary.BigEndian.Uint32(conn.packets[0][33:37]) != 2 { + t.Fatal("native offer was not restored before equipping") + } +} + +func TestShopCommitFailureRollsBackCashAndOwnership(t *testing.T) { + for _, trigger := range []string{ + "CREATE TRIGGER fail_sale BEFORE UPDATE OF credits ON players BEGIN SELECT RAISE(ABORT, 'cash failure'); END", + "CREATE TRIGGER fail_sale BEFORE DELETE ON items BEGIN SELECT RAISE(ABORT, 'item failure'); END", + } { + t.Run(trigger, func(t *testing.T) { + world, conn := newShopWorld(t) + client := world.clients[1] + world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + if _, err := world.db.Exec(trigger); err != nil { + t.Fatal(err) + } + conn.packets = nil + + err = world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]) + after, readErr := readTestItemStore(world) + + if err == nil || readErr != nil || !bytes.Equal(before, after) || len(conn.packets) != 0 || + world.characters[1].inventory.Credits != 100 || len(world.characters[1].inventory.Items) != 1 { + t.Fatalf("failed sale changed RAM, disk or sent success: save=%v read=%v", err, readErr) + } + }) + } +} + +func TestShopUseRejectsIneligibleAndForgedRequests(t *testing.T) { + for _, scenario := range []string{"Clan", "Neutral", "wrong zone", "too far", "dead", "loading", "unready", "replaced", "wrong owner", "wrong caller", "wrong machine", "wrong type", "reply", "wrong action", "11.0", "replay"} { + t.Run(scenario, func(t *testing.T) { + world, conn := newCombatWorld() + client, player := world.clients[1], world.characters[1] + player.position, player.appearance = [3]float32{60, 14.75, 53}, 0x515 + body := shopUseRequest(1) + switch scenario { + case "Clan": + player.appearance = 0x315 + case "Neutral": + player.appearance = 0x115 + case "wrong zone": + player.playfield = 952 + case "too far": + player.position[0] = 66 + case "dead": + player.health = 0 + case "loading": + client.loading = true + case "unready": + client.ready = false + case "replaced": + world.clients[1] = &worldClient{id: 1} + case "wrong owner": + binary.BigEndian.PutUint32(body[8:12], 2) + case "wrong caller": + binary.BigEndian.PutUint32(body[36:40], 2) + case "wrong machine": + binary.BigEndian.PutUint32(body[44:48], 0xc00003b8) + case "wrong type": + binary.BigEndian.PutUint32(body[40:44], 51059) + case "reply": + binary.BigEndian.PutUint32(body[16:20], 1) + case "wrong action": + binary.BigEndian.PutUint32(body[24:28], 4) + case "11.0": + client.target = false + case "replay": + client.useSequence = 1 + } + + err := world.handleShopUse(client, body) + + if err != nil || client.shop != nil || len(conn.packets) > 1 || len(conn.packets) == 1 && binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 { + t.Fatal("invalid use opened a shop") + } + }) + } +} + +func TestShopRejectsChangedOffersAndCreditOverflow(t *testing.T) { + for _, scenario := range []string{"moved", "changed count", "credit overflow", "too far", "dead", "faction changed"} { + t.Run(scenario, func(t *testing.T) { + world, _ := newShopWorld(t) + client, player := world.clients[1], world.characters[1] + world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]) + switch scenario { + case "moved": + player.inventory.Items[0].Slot = 65 + case "changed count": + player.inventory.Items[0].Count = 2 + case "credit overflow": + player.inventory.Credits = 999999999 + case "too far": + player.position[0] = 70 + case "dead": + player.health = 0 + case "faction changed": + player.appearance = 0x315 + } + before := player.inventory + + err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]) + + if err != nil || !reflect.DeepEqual(before, player.inventory) || client.shop != nil { + t.Fatal("invalidated offer was committed") + } + }) + } +} diff --git a/server/state.go b/server/state.go @@ -80,6 +80,7 @@ type worldClient struct { lootCorpse uint32 reclaimItems []uint32 backpacks map[uint32]backpackHandle + shop *shopTrade useSequence uint32 selectedTarget [2]uint32 teamInvitation *teamInvitation diff --git a/server/target_protocol.go b/server/target_protocol.go @@ -11,6 +11,10 @@ func targetPacket(packet []byte) []byte { // Convert the shared 11.0 messages to the recovered 14.9.1 wire layout. packet = packet[:binary.BigEndian.Uint16(packet[6:8])] switch binary.BigEndian.Uint32(packet[20:24]) { + case 0x36284f6e: + if binary.BigEndian.Uint32(packet[52:56]) == 104 { + binary.BigEndian.PutUint32(packet[56:60], binary.BigEndian.Uint32(packet[56:60])-16) + } case 0x5f4b1a39: // Playfield initialization ends after its two world origins. packet = packet[:93] @@ -157,6 +161,10 @@ func targetPacket(packet []byte) []byte { } func decodeInventory1491(body []byte) { + if len(body) == 40 && binary.BigEndian.Uint32(body) == 0x36284f6e && binary.BigEndian.Uint32(body[32:36]) == 104 { + binary.BigEndian.PutUint32(body[36:40], decodeInventorySlot1491(binary.BigEndian.Uint32(body[36:40]))) + return + } if (len(body) == 48 || len(body) == 56) && binary.BigEndian.Uint32(body) == 0x52526858 && binary.BigEndian.Uint32(body[40:44]) == 104 { binary.BigEndian.PutUint32(body[44:48], decodeInventorySlot1491(binary.BigEndian.Uint32(body[44:48]))) return