commit a09b87f4b9bc25540f42363652fd75d66f750a1d
parent aae635fdee471ec8975361c25475cb6096ccfde7
Author: anon <anon@example.com>
Date: Sun, 25 Oct 2026 05:29:40 +0000
Support documented Tools stock and atomic shop purchases
Diffstat:
8 files changed, 684 insertions(+), 35 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -558,15 +558,19 @@ introduction and starting-item gameplay remain open below.
Fresh clients after server restart retain the Omni/neutral poses and sale.
Original faction/profession/level/skill requirements share the template Use
evaluator; unsupported entitlement checks stay closed. See [vending machines
- and sales](docs/shops.md). Purchase stock remains separate work below.
+ and purchases](docs/shops.md). Complete purchase stock remains separate work below.
- [ ] Support shop vending machines. Check: using a shipped terminal opens
its native shop window with the correct stock and prices; purchases preserve
credits and item identity atomically, and insufficient credits or inventory
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. Recover
- the starter QETS category's actual membership; original descriptors identify
+- [x] Browse one vendor's documented fixed stock. The period Anarchy Arcanum
+ guide places QL 1 Lock Pick 95577 in Tools. The nine original OTIM templates
+ expose that entry; native Omni/Clan quotes use their own terminal modifiers.
+ Browsing allocates no owned item and spends no cash. This establishes one
+ entry, not complete Tools inventories or historical stock generation.
+- [ ] Recover complete historical shop stock, including the starter QETS
+ category's actual membership. Original descriptors identify
153 categories but do not establish their stock. Research online for shop
inventories, categories and QL ranges where the game data is insufficient,
and verify that the evidence applies to 14.9.1. Do not infer stock from names.
@@ -575,8 +579,17 @@ introduction and starting-item gameplay remain open below.
currently stay closed. Use one authoritative entitlement source for server
checks and native character stats; cover missing/granted/revoked entitlement
and revalidation of an open shop. Coordinate with the voice entitlement work.
-- [ ] Buy one item. Check: credits and inventory change together; insufficient
- credits or space leaves both unchanged.
+- [x] Buy one fixed simple item. Lock Pick purchases commit cash and durable
+ ownership together. Tests cover insufficient cash/space, mixed sale proceeds
+ and freed slots, cancellation/removal, Unique rules, forged references,
+ concurrent/repeated Accept, lost replies and SQLite failure/retry. Native
+ purchase icons and removal use a distinct catalog GUI tag. Pending-funds
+ checks prevent rapid Adds from creating invisible server selections.
+- [ ] Extend purchases to charged/partially used stacks, weapons, backpacks
+ and interpolated stock. Establish package sizes, slot packing, native live
+ object delivery and any merging rules before admitting these categories.
+ Cover full inventory, freed sale slots, partial failure and stable ownership
+ across reconnect/restart without inventing extra packet identity fields.
- [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 and restored room terminals support atomic sales,
@@ -587,7 +600,8 @@ introduction and starting-item gameplay remain open below.
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.
+ for on both successful and rejected paths. Include effective skill changes
+ while a basket is open and removal of the sale funding a selected purchase.
- [ ] Refresh one vendor's stock. Check: the intended stock policy updates the
list without changing an already purchased item's identity or properties.
diff --git a/docs/shops.md b/docs/shops.md
@@ -1,10 +1,11 @@
-# Vending machines and sales
+# Vending machines, purchases and sales
The server restores the original vending-machine placements and accepts 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.
+Cancel and removing an offer restore the same item. Tools terminals expose a
+documented fixed Lock Pick entry and accept purchases. Complete historical
+stock membership, random generation and stock rotation remain unresolved.
## Original placements and access
@@ -25,8 +26,8 @@ developer worlds remain unavailable; their source records do not grant entry.
Every target-client entry sends only that playfield's authored objects. The
same registry resolves Use and supplies the active trade's template and sale
-modifier. Trades retain only the machine identity, so opening and completing
-a sale share the same immutable contract.
+modifier. Trades retain the machine identity and catalog indices, so opening
+and completing a transaction share the same immutable contract.
Native default interaction `N3Msg_DefaultActionOnDynel` at 0x1002c350 requires
Can stat 30 mask 8 before dispatching Use. This also rejects forged Use requests
@@ -64,6 +65,86 @@ 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.
+## Documented fixed stock and purchases
+
+The original Anarchy Arcanum NCU Hacker Interface guide, updated 19 February
+2003 and [captured 7 March 2003](https://web.archive.org/web/20030307043050id_/http://home.c2i.net:80/ellusion/gadgets_ncuhackerinterface.html),
+explicitly places Lock Pick in the local Tools booth. Original item 95577 is
+Lock Pick, fixed QL 1, type 51005, price stat 74 equal to 230. The nine original
+Tools templates share category OTIM. `shop_stock.yaml` supplies that documented
+fixed entry to those catalogs; it does not claim to recover their complete
+inventories, original random selection or refresh policy. Unknown categories
+retain their working sales without invented purchase entries.
+
+The same period guide places Nano Programming Interface in a Devices booth.
+A later guide places it in Tools; that later wording is insufficient to change
+the period mapping, so the interface is not admitted. The original public
+2002 domain pages are framesets pointing to the separately archived content
+host. Exact captures, CDX metadata, original item bytes and hashes are retained
+under `local/shop-purchase-research/sources/`. The later emulator's full stock
+tables include expansion data and are not imported as historical truth.
+
+ShopUpdate key 0x58362220 belongs to the selected machine. Its body is a count
+token `(entries + 1) * 1009`, followed by low template, high template and QL
+for each entry. It contains neither prices nor owned identities. The native
+client computes quotes from the original item, terminal and character stats.
+Catalog row identities are `(111,index)`, in packet order. Each purchase Add
+or Remove selects one package using A=machine, B=that catalog reference. The
+server retains the catalog for the life of the draft and validates page,
+index, machine identity, quantities and Unique acquisition.
+
+The native Add echo receiver repeats its affordability check and silently
+ignores an unaffordable purchase. The server checks the same pending basket
+cost before acknowledging Add; an excess aborts the draft. This prevents
+rapid requests from creating a server selection absent from the native basket.
+KKR 0x100a9f60 credits each pending sale row once, without charge normalization
+or count, using signed price and terminal modifier:
+
+```
+base = T(signedItemPrice * signedTerminalStat426 * binary64(0.01))
+markup = T(effectiveComputerLiteracy * float32(0.025))
+pendingSaleCredit = base + T(markup * base * float32(0.01))
+```
+
+The native sentinel price 1234567890 contributes zero. This admission formula
+differs from the displayed and accepted sale calculations below; it does not
+replace the authoritative funds check on Accept.
+
+For the current fixed simple-item entries, Accept creates one durable owned
+record per selected package. It validates eligibility, all offered sale items,
+net funds, final inventory capacity and Unique ownership again. Sold items,
+purchased instances and the resulting cash commit in the same SQLite
+transaction. Sale proceeds can fund a purchase and vacated sale slots can hold
+its result. Rejection or a database failure publishes none of those changes;
+concurrent/repeated Accept or a lost reply cannot allocate another instance.
+
+Complete clears the native selection and consumes staged sales; it does not
+create purchases or debit cash. After the durable commit the server sends
+Complete, AddTemplate for each purchase, and absolute cash stat 61. AddTemplate
+carries `{low,high,QL,count}` and initially creates a native template entry with
+null instance identity. The durable server item identity survives reconnect,
+whose full inventory supplies it. No extra ID word is invented in either
+packet. Delivery and package packing for charged stacks, weapons, containers
+and interpolated stock remain separate work; current stock admission tests
+require exact, nonstacking type 51005 items.
+
+The buy quote recovered from KKR 0x100a9610 is:
+
+```
+base = T(itemPrice * terminalStat427 * binary64(0.01))
+discount = min(T(effectiveComputerLiteracy * float32(0.025)), 90)
+unitQuote = base - T(discount * base * float32(0.01))
+lineQuote = unitQuote * selectedPackages
+```
+
+Discounts round per package, not once after multiplying quantity. Negative
+Computer Literacy retains the observed signed arithmetic, and the original
+90-percent cap takes precedence over later guides. Charging the quoted line
+total on Accept is the reconstruction policy: a distinct historical server
+debit algorithm was not recovered. The finalizer inspected in the client
+contains no purchase debit. Native procedures, fields and remaining boundaries
+are recorded in `local/shop-purchase-research/native/README.md`.
+
## Native handshake and inventory references
The target is `anarchy-vanilla-14.9.1/kkr.dll`, SHA-256
@@ -84,9 +165,19 @@ 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.
+2. Player-subject Trade action 0, A=machine, B=(111,0), opens shop mode.
+ DDR TradeViewModule startup 0x100485b0 uses nonzero B as a catalog GUI tag.
+ A zero B selects ordinary player trading and omits shop credit displays.
+
+DDR refresh 0x10048f50 fetches catalog and purchase entries using A, then
+passes B only to classify catalog rows. Row renderer 0x10048a20 compares that
+tag before either basket owner. Giving B the same identity as A causes selected
+purchase rows to alias the catalog and leaves the buy grid blank despite its
+updated cost. B must also differ from the player sale owner. The original
+server's precise tag was not recovered; `(111,0)` is an explicit reconstruction
+choice using the native catalog namespace. Actual purchase Add/Remove still
+address A=machine. The retained evidence is
+`local/shop-purchase-research/native/ui-basket.md`.
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
@@ -103,9 +194,9 @@ 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.
+An empty ShopUpdate would print the original "contact a GM" warning. Categories
+without documented stock omit that update. Native empty catalog and
+purchase-basket lists still permit sale offers.
Evidence is retained under `local/shop-research/wire/`. Key records:
@@ -177,6 +268,15 @@ stale items, NoDrop, backpacks, forged identities/actions, session replacement,
faction/range/life checks, overflow, concurrent Accept, lost replies, SQLite
write failures and equipping an offered item.
+`server/shop_purchases_test.go` covers catalog tuples and independent GUI tags,
+buy-price boundaries including negative skill and the native discount cap,
+multiple selected packages and removal, cancellation, insufficient cash and
+space, forged catalog references, Unique acquisition, mixed sale funding and
+freed slots, concurrent/repeated confirmation, lost replies and SQLite failure
+with retry. Rapid unfunded Adds abort before they can leave a server purchase
+absent from the native basket. Stock admission tests keep unverified charged,
+weapon and container delivery outside the fixed simple-item catalog.
+
Two headed Chromium WASM clients ran on the GPU. Before restoration,
Omni room 1183 had the static identity but no native vending object or visible
machine. After restoration, native object-tree and vehicle reads matched all
@@ -195,8 +295,26 @@ same item remained in SQLite and cash stayed 100. Accept removed it and changed
both native and persisted cash to 834. A fresh WASM connection retained 834 and
an empty inventory. A server restart followed by fresh WASM clients retained
all 131 Omni/neutral poses and appearances and the same committed sale.
-Stock remains intentionally empty pending membership
-research; this verification does not establish purchasing or stock refresh.
+This placement and sale run preceded the fixed purchase catalog. Historical
+stock generation and refresh remain unresolved.
+
+The purchase run used two fresh headed GPU WASM clients. Omni Tools
+3221488799 quoted 228 credits for Lock Pick and Clan Tools 3223651484 quoted
+239 at effective Computer Literacy 40. Accept delivered one item and left
+772 and 761 credits respectively. Reconnect and a server restart retained the
+same durable instances. With the distinct catalog tag, actual mouse clicks
+displayed a BUY icon, selected two Clan packages for 478, removed one to leave
+239, and cancelled without changing cash or ownership.
+
+A mixed Omni basket started with zero cash, offered axe 101 for 734 and
+selected a lockpick for 228. SQLite retained the axe and zero cash while the
+draft was open. Accept replaced the axe with lockpick 102 in its freed slot
+and changed both native and persisted cash to 506. Reconnect and fresh clients
+after another cold server restart retained all purchase identities and
+balances. A later attempted third package exceeded 506 credits; the native
+input path retained only two selections at 456, and cancellation preserved
+every owned item and credit. Wire captures confirm real Add/Remove messages,
+Complete followed by AddTemplate and absolute cash, with no client errors.
`local/shop-room-research/` retains the independent catalog audit, reproducible
extraction provenance and original-client access evidence.
@@ -205,10 +323,12 @@ snapshots and complete WebSocket traces with reconnect/replay handling. The
checks use genuine native objects and input; no clickable proxy or client
source change was required. Owned test clients are closed between runs, and
the dummy-HDMI display's power-saving state is restored afterward.
+`local/shop-purchase-smoke/` retains the purchase screenshots, native/database
+snapshots, WebSocket captures and assertion script.
-The complete tracked Go suite passed (server 697 seconds, gamedata 8 seconds),
-as did the shop/shared-requirements race checks (175 seconds), the additional
-specialist-sale race checks (98 seconds), and `go vet -stdversion=false`.
+The complete tracked Go suite passed (server 739 seconds, gamedata 8 seconds).
+After the final GUI-tag correction, all shop checks passed again under the race
+detector (176 seconds), as did `go vet -stdversion=false`.
Cleanup removed only the two test-owned players. All unrelated database rows
were unchanged, foreign-key and integrity checks passed, and the single shared
HTTPS preview remains available on port 8443.
diff --git a/server/gamedata/load.go b/server/gamedata/load.go
@@ -30,6 +30,7 @@ var (
TerrainEvidence TerrainExtractionEvidence
Playfields map[uint32]Playfield
ShopMachines map[uint32]ShopMachine
+ ShopStock map[string][]uint32
PlayerAppearances struct {
Heads []PlayerHead `yaml:"heads"`
Bodies []PlayerBody `yaml:"bodies"`
@@ -79,6 +80,7 @@ func init() {
loadYAML("player_appearances.yaml", &PlayerAppearances)
loadYAML("banks.yaml", &BankTerminals)
loadYAML("shops.yaml", &ShopMachines)
+ loadYAML("shop_stock.yaml", &ShopStock)
loadYAML("profession_resources.yaml", &ProfessionTitles)
loadYAML("experience.yaml", &ExperienceLevels)
loadYAML("ip_training.yaml", &IPTraining)
diff --git a/server/gamedata/shop_stock.yaml b/server/gamedata/shop_stock.yaml
@@ -0,0 +1,4 @@
+# Documented fixed stock; other category membership remains unresolved.
+# Lock Pick: Anarchy Arcanum, NCU Hacker Interface, updated 19 February 2003.
+# Original item 95577 has one fixed QL. See docs/shops.md for source provenance.
+OTIM: [95577]
diff --git a/server/shop_machines_test.go b/server/shop_machines_test.go
@@ -58,7 +58,8 @@ func TestShopUseEvaluatesAuthoredAccessContracts(t *testing.T) {
t.Fatalf("shop admission = %v, want %v", client.shop != nil, scenario.accepted)
}
if scenario.accepted {
- if len(conn.packets) != 4 || client.shop.machine != scenario.machine || binary.BigEndian.Uint32(conn.packets[3][49:53]) != scenario.machine {
+ if len(conn.packets) != 4 || client.shop.machine != scenario.machine || binary.BigEndian.Uint32(conn.packets[3][41:45]) != scenario.machine ||
+ binary.BigEndian.Uint32(conn.packets[3][45:49]) != 111 || binary.BigEndian.Uint32(conn.packets[3][49:53]) != 0 {
t.Fatal("opened the wrong shop contract")
}
} else if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 {
diff --git a/server/shop_purchases_test.go b/server/shop_purchases_test.go
@@ -0,0 +1,372 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "encoding/binary"
+ "reflect"
+ "slices"
+ "sync"
+ "testing"
+)
+
+func newPurchaseWorld(t *testing.T) (*server, *combatTestConn) {
+ t.Helper()
+ world, conn := newEquipmentWorld(t)
+ player := world.characters[1]
+ player.playfield, player.position, player.appearance = 1183, [3]float32{188, 5.75, 135.5}, 0x515
+ player.inventory.Credits = 1000
+ player.stats.Abilities.Intelligence = 5
+ player.stats.TradeRepair.ComputerLiteracy = 39
+ 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)
+ }
+ request := shopUseRequest(1)
+ binary.BigEndian.PutUint32(request[44:48], 3221488799)
+ if err := world.handleShopUse(world.clients[1], request); err != nil {
+ t.Fatal(err)
+ }
+ return world, conn
+}
+
+func TestShopCatalogUsesOriginalPageIndicesAndExactTemplates(t *testing.T) {
+ world, conn := newPurchaseWorld(t)
+
+ if len(conn.packets) != 5 || world.clients[1].shop == nil {
+ t.Fatalf("catalog initialization: %x", conn.packets)
+ }
+ packet := conn.packets[2]
+ if binary.BigEndian.Uint32(packet[16:20]) != 0x58362220 || binary.BigEndian.Uint32(packet[20:24]) != 51035 || binary.BigEndian.Uint32(packet[24:28]) != 3221488799 {
+ t.Fatal("catalog belongs to the wrong machine")
+ }
+ for index, expected := range []uint32{2018, 95577, 95577, 1} {
+ if binary.BigEndian.Uint32(packet[29+index*4:]) != expected {
+ t.Fatalf("catalog field %d changed", index)
+ }
+ }
+ start := conn.packets[4]
+ if binary.BigEndian.Uint32(start[37:41]) != 51035 || binary.BigEndian.Uint32(start[41:45]) != 3221488799 ||
+ binary.BigEndian.Uint32(start[45:49]) != 111 || binary.BigEndian.Uint32(start[49:53]) != 0 {
+ t.Fatal("catalog GUI tag aliases a basket owner and hides selected rows")
+ }
+ if len(world.characters[1].inventory.Items) != 1 || world.nextItem != 1 || world.characters[1].inventory.Credits != 1000 {
+ t.Fatal("browsing changed ownership or cash")
+ }
+}
+
+func TestShopKnownStockOnlyAdmitsSupportedFixedSimpleItems(t *testing.T) {
+ for _, templates := range gamedata.ShopStock {
+ for _, template := range templates {
+ definition := gamedata.ItemTemplates[template]
+ if definition == nil || definition.Quality == nil || definition.HeaderWords[0] != 51005 || int32(itemStat(definition, 212)) > 0 {
+ t.Fatalf("stock %d needs a separately verified delivery/packing path", template)
+ }
+ }
+ }
+}
+
+func TestShopBuyQuotesMatchNativePerPackageRounding(t *testing.T) {
+ for _, scenario := range []struct {
+ literacy int32
+ credits uint64
+ }{
+ {-40, 232}, {0, 230}, {39, 230}, {40, 228}, {80, 226}, {3200, 47}, {3600, 24}, {4000, 24},
+ } {
+ item := ownedItem{Template: 95577, Quality: 1}
+ price := shopBuyPrice(item, 100, scenario.literacy)
+ if price != scenario.credits {
+ t.Fatalf("CL%d quote %d, want %d", scenario.literacy, price, scenario.credits)
+ }
+ }
+}
+
+func TestShopPurchasePersistsOnceAfterRepeatedConcurrentAccept(t *testing.T) {
+ world, conn := newPurchaseWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:]
+ remove := shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:]
+ accept := shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]
+ for _, body := range [][]byte{add, add, remove} {
+ if err := world.handleShopTrade(client, body); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if player.inventory.Credits != 1000 || len(player.inventory.Items) != 1 || world.nextItem != 1 {
+ t.Fatal("draft purchase allocated ownership or debited cash")
+ }
+ conn.packets = nil
+
+ var requests sync.WaitGroup
+ errors := make(chan error, 2)
+ 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)
+ }
+ }
+ world.handleShopTrade(client, accept)
+ restored := newTestInventoryServer(t).characters[1].inventory
+
+ if restored.Credits != 772 || len(restored.Items) != 2 || restored.Items[1] != (ownedItem{ID: 2, Type: 51005, Template: 95577, Quality: 1, Slot: 65, Count: 1}) || world.nextItem != 2 || !reflect.DeepEqual(restored.Items, player.inventory.Items) {
+ t.Fatalf("purchase did not commit exactly once: %+v", restored)
+ }
+ if len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[0][33:37]) != 3 || binary.BigEndian.Uint32(conn.packets[1][16:20]) != 0x052e2f0c || binary.BigEndian.Uint32(conn.packets[2][33:37]) != 772 {
+ t.Fatal("purchase delivery/completion/cash ordering changed")
+ }
+}
+
+func TestShopPurchaseCancelAndRemoveLeaveCashAndOwnershipUnchanged(t *testing.T) {
+ for _, cancel := range []bool{false, true} {
+ t.Run(map[bool]string{false: "remove", true: "cancel"}[cancel], func(t *testing.T) {
+ world, _ := newPurchaseWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ before := slices.Clone(player.inventory.Items)
+ add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:]
+ if err := world.handleShopTrade(client, add); err != nil {
+ t.Fatal(err)
+ }
+ request := shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:]
+ if cancel {
+ request = shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]
+ }
+
+ err := world.handleShopTrade(client, request)
+ if !cancel {
+ err = world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ }
+ restored := newTestInventoryServer(t).characters[1].inventory
+
+ if err != nil || restored.Credits != 1000 || !reflect.DeepEqual(restored.Items, before) || world.nextItem != 1 {
+ t.Fatalf("cancel/remove changed inventory: %v %+v", err, restored)
+ }
+ })
+ }
+}
+
+func TestShopPurchaseRejectsInsufficientCashAndFullInventoryAtomically(t *testing.T) {
+ for _, scenario := range []string{"insufficient cash", "full inventory", "two packages one slot", "eligibility changed"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newPurchaseWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:]
+ world.handleShopTrade(client, add)
+ switch scenario {
+ case "insufficient cash":
+ player.inventory.Credits = 227
+ case "eligibility changed":
+ player.appearance = 0x315
+ default:
+ last := uint32(94)
+ if scenario == "two packages one slot" {
+ last = 93
+ world.handleShopTrade(client, add)
+ }
+ for slot := uint32(65); slot < last; slot++ {
+ item := player.inventory.Items[0]
+ item.ID, item.Slot = slot-63, slot
+ player.inventory.Items = append(player.inventory.Items, item)
+ }
+ player.inventory.LastID = uint32(len(player.inventory.Items))
+ }
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ before := player.inventory
+ before.Items = slices.Clone(before.Items)
+ next := world.nextItem
+
+ err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ restored := newTestInventoryServer(t).characters[1].inventory
+
+ if err != nil || client.shop != nil || world.nextItem != next || !reflect.DeepEqual(player.inventory, before) || restored.Credits != before.Credits || !reflect.DeepEqual(restored.Items, before.Items) {
+ t.Fatalf("rejected purchase changed cash/ownership: %v %+v", err, restored)
+ }
+ })
+ }
+}
+
+func TestShopPurchaseRejectsForgedCatalogReferences(t *testing.T) {
+ for _, scenario := range []string{"unknown index", "wrong page", "wrong machine", "wrong subject", "empty remove"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newPurchaseWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ first, second := [2]uint32{51035, 3221488799}, [2]uint32{111, 0}
+ action := uint32(4)
+ switch scenario {
+ case "unknown index":
+ second[1] = 1
+ case "wrong page":
+ second[0] = 104
+ case "wrong machine":
+ first[1] = 3221226655
+ case "wrong subject":
+ first[0] = 50000
+ case "empty remove":
+ action = 5
+ }
+
+ err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, action, first, second)[20:])
+
+ if err != nil || client.shop != nil || player.inventory.Credits != 1000 || len(player.inventory.Items) != 1 || world.nextItem != 1 {
+ t.Fatal("forged catalog reference changed ownership")
+ }
+ })
+ }
+}
+
+func TestShopPurchaseCommitFailureCanRetryWithoutAllocatingTwice(t *testing.T) {
+ world, _ := newPurchaseWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:])
+ if _, err := world.db.Exec("CREATE TRIGGER fail_purchase BEFORE UPDATE OF credits ON players BEGIN SELECT RAISE(ABORT, 'cash failure'); END"); err != nil {
+ t.Fatal(err)
+ }
+ accept := shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]
+
+ failed := world.handleShopTrade(client, accept)
+ if failed == nil || player.inventory.Credits != 1000 || len(player.inventory.Items) != 1 || world.nextItem != 1 || client.shop == nil {
+ t.Fatal("failed transaction published purchase state")
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_purchase"); err != nil {
+ t.Fatal(err)
+ }
+ err := world.handleShopTrade(client, accept)
+ restored := newTestInventoryServer(t).characters[1].inventory
+
+ if err != nil || restored.Credits != 772 || len(restored.Items) != 2 || restored.Items[1].ID != 2 || world.nextItem != 2 {
+ t.Fatalf("purchase retry duplicated allocation: %v %+v", err, restored)
+ }
+}
+
+func TestShopMixedBasketUsesSaleProceedsAndFreedInventorySlot(t *testing.T) {
+ world, _ := newPurchaseWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ player.inventory.Credits = 0
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ for _, request := range [][]byte{
+ shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:],
+ shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:],
+ } {
+ if err := world.handleShopTrade(client, request); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ restored := newTestInventoryServer(t).characters[1].inventory
+
+ if err != nil || restored.Credits != 506 || len(restored.Items) != 1 || restored.Items[0] != (ownedItem{ID: 2, Type: 51005, Template: 95577, Quality: 1, Slot: 64, Count: 1}) {
+ t.Fatalf("mixed basket did not balance ownership and credits: %v %+v", err, restored)
+ }
+}
+
+func TestShopLostPurchaseReplyPreservesExactlyOneOwnedInstance(t *testing.T) {
+ world, _ := newPurchaseWorld(t)
+ client := world.clients[1]
+ world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[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 || client.shop != nil || restored.Credits != 772 || len(restored.Items) != 2 || restored.Items[1].ID != 2 || world.nextItem != 2 {
+ t.Fatal("lost purchase completion lost or duplicated the committed item")
+ }
+}
+
+func TestShopPurchaseUniqueChecksCarriedItemsAndBasket(t *testing.T) {
+ for _, scenario := range []string{"already carried", "selected twice", "acquired after offer"} {
+ t.Run(scenario, func(t *testing.T) {
+ original := gamedata.ItemTemplates[95577]
+ definition := *original
+ definition.Stats = slices.Clone(original.Stats)
+ for index, stat := range definition.Stats {
+ if stat[0] == 0 {
+ definition.Stats[index][1] |= 0x08000000
+ }
+ }
+ gamedata.ItemTemplates[95577] = &definition
+ defer func() { gamedata.ItemTemplates[95577] = original }()
+ world, _ := newPurchaseWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:]
+ if scenario != "already carried" {
+ if err := world.handleShopTrade(client, add); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if scenario != "selected twice" {
+ if granted, err := world.grantItem_locked(player, 95577); err != nil || !granted {
+ t.Fatalf("unique fixture: %v", err)
+ }
+ }
+ before := slices.Clone(player.inventory.Items)
+ next := world.nextItem
+ request := add
+ if scenario == "acquired after offer" {
+ request = shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]
+ }
+
+ err := world.handleShopTrade(client, request)
+
+ if err != nil || client.shop != nil || player.inventory.Credits != 1000 || world.nextItem != next || !reflect.DeepEqual(before, player.inventory.Items) {
+ t.Fatal("unique purchase duplicated carried ownership")
+ }
+ })
+ }
+}
+
+func TestShopRapidUnfundedAddsCannotCreateInvisiblePurchases(t *testing.T) {
+ world, conn := newPurchaseWorld(t)
+ client, player := world.clients[1], world.characters[1]
+ player.inventory.Credits = 300
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:]
+ conn.packets = nil
+
+ for _, request := range [][]byte{
+ add, add,
+ shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:],
+ shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:],
+ } {
+ if err := world.handleShopTrade(client, request); err != nil {
+ t.Fatal(err)
+ }
+ }
+ restored := newTestInventoryServer(t).characters[1].inventory
+
+ if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][33:37]) != 4 || binary.BigEndian.Uint32(conn.packets[1][33:37]) != 2 || client.shop != nil || world.nextItem != 1 || restored.Credits != 300 || len(restored.Items) != 1 || restored.Items[0].ID != 1 {
+ t.Fatal("rapid Adds left a hidden purchase that later sale proceeds could fund")
+ }
+}
+
+func TestShopPendingSaleFundingRetainsNativeSignedRowArithmetic(t *testing.T) {
+ for _, scenario := range []struct {
+ count uint16
+ literacy int32
+ credits int64
+ }{
+ {1, 0, 727}, {2, 0, 727}, {1, 40, 734}, {2, 40, 734}, {1, -40, 720}, {1, -4000, 1}, {1, -4040, -7},
+ } {
+ item := ownedItem{Template: 209283, Quality: 1, Type: 51018, Count: scenario.count}
+ credits := shopPendingSalePrice(item, 6, scenario.literacy)
+ if credits != scenario.credits {
+ t.Fatalf("pending row count%d CL%d credited %d, want %d", scenario.count, scenario.literacy, credits, scenario.credits)
+ }
+ }
+}
diff --git a/server/shops.go b/server/shops.go
@@ -10,8 +10,27 @@ import (
)
type shopTrade struct {
- machine uint32
- items map[uint32]ownedItem
+ machine uint32
+ items map[uint32]ownedItem
+ stock []uint32
+ purchases map[uint32]uint16
+}
+
+func shopStock(definition *gamedata.Item) []uint32 {
+ var stock []uint32
+ for _, section := range definition.Sections {
+ if section.Type != 23 || section.Subtype != 37 || section.Entries == nil {
+ continue
+ }
+ for _, entry := range *section.Entries {
+ for _, template := range gamedata.ShopStock[*entry.Code] {
+ if !slices.Contains(stock, template) {
+ stock = append(stock, template)
+ }
+ }
+ }
+ }
+ return stock
}
func (server *server) canUseShop_locked(client *worldClient, machine gamedata.ShopMachine) bool {
@@ -105,17 +124,30 @@ func (server *server) handleShopUse(client *worldClient, body []byte) error {
return err
}
}
- client.shop = &shopTrade{machine: machineID, items: make(map[uint32]ownedItem)}
+ client.shop = &shopTrade{machine: machineID, items: make(map[uint32]ownedItem), stock: shopStock(gamedata.ItemTemplates[machine.Template]), purchases: make(map[uint32]uint16)}
if err := client.send(shopMachinePacket(machineID, machine)); err != nil {
return err
}
+ // Unknown categories omit ShopUpdate; an empty update prints a native GM warning.
+ if len(client.shop.stock) != 0 {
+ // Native catalog entries are page111 indices, without owned instance IDs.
+ catalog := binary.BigEndian.AppendUint32(nil, uint32(len(client.shop.stock)+1)*1009)
+ for _, template := range client.shop.stock {
+ for _, value := range []uint32{template, template, *gamedata.ItemTemplates[template].Quality} {
+ catalog = binary.BigEndian.AppendUint32(catalog, value)
+ }
+ }
+ if err := client.send(n3Packet(0x58362220, 51035, machineID, catalog)); 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, machineID}, 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 membership is unresolved; no purchase catalog is invented.
- return client.send(shopTradePacket([2]uint32{50000, client.id}, 0, [2]uint32{51035, machineID}, [2]uint32{51035, machineID}))
+ // DDR uses B as the catalog's GUI tag. It must differ from the machine
+ // identity so selected rows reach the purchase grid rather than the catalog.
+ return client.send(shopTradePacket([2]uint32{50000, client.id}, 0, [2]uint32{51035, machineID}, [2]uint32{111, 0}))
}
func (server *server) abortShop_locked(client *worldClient) error {
@@ -151,6 +183,24 @@ func shopSalePrice(item ownedItem, modifier uint32, computerLiteracy int32) uint
return uint64(max(0, int64(base)+int64(float64(markup)*float64(float32(0.01))*float64(base))))
}
+func shopBuyPrice(item ownedItem, modifier uint32, computerLiteracy int32) uint64 {
+ // kkr.dll 100a9610 discounts each package, with a ninety-percent cap.
+ base := int64(float64(item.shopPrice()) * float64(modifier) * 0.01)
+ discount := min(int64(float64(computerLiteracy)*float64(float32(0.025))), 90)
+ return uint64(base - int64(float64(discount)*float64(base)*float64(float32(0.01))))
+}
+
+func shopPendingSalePrice(item ownedItem, modifier uint32, computerLiteracy int32) int64 {
+ // kkr.dll 100a9f60 uses one signed price per offered row, without charges/count.
+ price := int32(item.shopPrice())
+ if price == 1234567890 {
+ price = 0
+ }
+ base := int64(float64(price) * float64(int32(modifier)) * 0.01)
+ markup := int64(float64(computerLiteracy) * float64(float32(0.025)))
+ return base + int64(float64(markup)*float64(base)*float64(float32(0.01)))
+}
+
func (server *server) handleShopTrade(client *worldClient, body []byte) error {
if len(body) != 40 {
return fmt.Errorf("invalid trade length")
@@ -171,6 +221,46 @@ func (server *server) handleShopTrade(client *worldClient, body []byte) error {
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])}
+ if (action == 4 || action == 5) && first == [2]uint32{51035, client.shop.machine} {
+ if second[0] != 111 || second[1] >= uint32(len(client.shop.stock)) {
+ return server.abortShop_locked(client)
+ }
+ // Each native Add/Remove selects one package, using a signed-short count.
+ count := client.shop.purchases[second[1]]
+ if action == 4 {
+ if count == 32767 {
+ return server.abortShop_locked(client)
+ }
+ template := client.shop.stock[second[1]]
+ definition := gamedata.ItemTemplates[template]
+ item := ownedItem{Template: template, Quality: *definition.Quality}
+ if itemStat(definition, 0)&0x08000000 != 0 && (count != 0 || player.inventory.carriesUnique(item)) {
+ return server.abortShop_locked(client)
+ }
+ // The native echo receiver ignores unaffordable Adds. Match its pending
+ // calculation before acknowledging so rapid requests cannot hide purchases.
+ literacy := player.effectiveSkill(161, player.stats.TradeRepair.ComputerLiteracy, [6]uint32{0, 0, 0, 100, 0, 0})
+ vendor := gamedata.ItemTemplates[machine.Template]
+ cost := int64(shopBuyPrice(item, itemStat(vendor, 427), literacy))
+ for index, packages := range client.shop.purchases {
+ other := gamedata.ItemTemplates[client.shop.stock[index]]
+ cost += int64(shopBuyPrice(ownedItem{Template: other.ID, Quality: *other.Quality}, itemStat(vendor, 427), literacy)) * int64(packages)
+ }
+ for _, offered := range client.shop.items {
+ cost -= shopPendingSalePrice(offered, itemStat(vendor, 426), literacy)
+ }
+ if cost > int64(player.inventory.Credits) {
+ return server.abortShop_locked(client)
+ }
+ client.shop.purchases[second[1]] = count + 1
+ } else {
+ if count == 0 {
+ return server.abortShop_locked(client)
+ }
+ client.shop.purchases[second[1]] = count - 1
+ }
+ return client.send(shopTradePacket([2]uint32{50000, client.id}, action, first, second))
+ }
switch action {
case 4:
if first != [2]uint32{50000, client.id} || second[0] != 104 || second[1] < 64 || second[1] >= 94 {
@@ -232,20 +322,66 @@ func (server *server) handleShopTrade(client *worldClient, body []byte) error {
credits += shopSalePrice(item, modifier, literacy)
inventory.Items = slices.Delete(inventory.Items, index, index+1)
}
- if credits > uint64(1000000000-inventory.Credits) {
+ // Allocate purchases only in the prospective inventory. Any failure cancels
+ // the whole basket before cash, identities or ownership become observable.
+ var cost uint64
+ nextItem := server.nextItem
+ var purchased []ownedItem
+ for index, template := range client.shop.stock {
+ definition := gamedata.ItemTemplates[template]
+ item := ownedItem{Type: definition.HeaderWords[0], Template: template, Quality: *definition.Quality, Count: 1}
+ count := client.shop.purchases[uint32(index)]
+ cost += shopBuyPrice(item, itemStat(gamedata.ItemTemplates[machine.Template], 427), literacy) * uint64(count)
+ for range count {
+ if itemStat(definition, 0)&0x08000000 != 0 && inventory.carriesUnique(item) {
+ return server.abortShop_locked(client)
+ }
+ item.Slot = 64
+ for item.Slot < 94 && slices.ContainsFunc(inventory.Items, func(other ownedItem) bool { return other.Slot == item.Slot }) {
+ item.Slot++
+ }
+ if item.Slot == 94 {
+ return server.abortShop_locked(client)
+ }
+ if nextItem == ^uint32(0) {
+ return fmt.Errorf("item identities exhausted")
+ }
+ nextItem++
+ item.ID = nextItem
+ inventory.Items = append(inventory.Items, item)
+ purchased = append(purchased, item)
+ }
+ }
+ balance := uint64(inventory.Credits) + credits
+ if cost > balance || balance-cost > 1000000000 {
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 {
+ inventory.Credits = uint32(balance - cost)
+ if len(purchased) != 0 {
+ inventory.LastID = nextItem
+ }
+ // Sales, purchases and cash share the existing SQLite transaction.
+ if len(client.shop.items) != 0 || len(purchased) != 0 {
if err := server.saveInventory_locked(player, inventory); err != nil {
return err
}
+ server.nextItem = nextItem
}
client.shop = nil
if err := client.send(shopTradePacket([2]uint32{50000, client.id}, 3, [2]uint32{}, [2]uint32{})); err != nil {
return err
}
+ // AddTemplate chooses first-free slots, matching the allocation above.
+ // Native catalog entries have no instance identity; durable IDs live in SQLite.
+ for _, item := range purchased {
+ var body []byte
+ for _, value := range []uint32{item.Template, item.Template, item.Quality, 1} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ if err := client.send(n3Packet(0x052e2f0c, 50000, client.id, body)); 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))
diff --git a/server/shops_test.go b/server/shops_test.go
@@ -115,7 +115,7 @@ func TestShopNativeSocketUseAndSale(t *testing.T) {
}
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) {
+ binary.BigEndian.Uint32(packet[45:49]) != 111 || binary.BigEndian.Uint32(packet[49:53]) != 0) {
t.Fatalf("player trade window has the wrong partner: %x", packet)
}
}