commit 5365d90a9ee4a2db323d165e4a12fb02ba1206b1
parent 12415697ade471ce9912f4f4334ebf165ef9f206
Author: anon <anon@example.com>
Date: Sun, 25 Oct 2026 09:16:47 +0000
Implement atomic native player item and credit trading
Diffstat:
28 files changed, 1345 insertions(+), 157 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -957,16 +957,26 @@ and unresolved indoor lifecycle are explicit in [flight](docs/vehicles.md#yalmah
- [x] Recover the original player-trade message topology, first-free placement,
one-shot acceptance and filled-backpack restrictions. The protocol ledger
and explicit remaining limits are in [player trading](docs/player-trading.md).
-- [ ] Recover and verify peer template-stack delivery before enabling trades.
- Native Add7 creates a count-one row; correcting ordinary inventory only after
- completion does not fix the quantity shown before consent. Test partial/full
- charged stacks, actual IDs, QL, ammunition and both native basket views.
-- [ ] Open a two-player trade. Check: both native windows refer to the correct
- participants and offered items remain unavailable for conflicting transfers.
-- [ ] Complete an item-for-item trade. Check: both confirmations transfer items
- together; cancellation leaves original ownership unchanged.
-- [ ] Include credits in a trade. Check: credit and item transfers commit
- together, with no negative balance or repeated transfer.
+- [x] Recover and verify peer template-stack delivery. Remote AddTemplate plus
+ Trade4 preserves the count in both native baskets and at completion. Partial
+ charges, interpolated QL endpoints, loaded ammunition and stable durable IDs
+ have regression coverage; two hardware WASM clients verified 25/50 charges.
+- [x] Open a two-player trade. Both native windows identify the participants;
+ held offers reject conflicting use, inventory, bank, shop and loot operations.
+ Disconnect, death, control edits and leaving range cancel the shared draft.
+- [x] Complete item-for-item trades and gifts. Both confirmations transfer items
+ atomically; cancellation restores first-free placement without changing
+ ownership. Native tests include filled backpacks, Unique/NoDrop rejection,
+ reconnect and 32 offer/cancel cycles without accumulating remote rows.
+- [x] Include credits in a trade. Both balances and item ownership commit in one
+ transaction. Tests cover native Cash6-on-Accept, bounds, overflow, failed
+ persistence, concurrent/replayed acceptance and lost completion replies.
+- [ ] Recover native feedback for rejected player trades, including a full
+ recipient inventory and duplicate Unique items. Current rejection safely
+ closes the trade; show an evidenced reason through the original client.
+- [ ] Establish remaining historical trade policies: Unique counting across
+ bank/reclaim, acceptance edits and server-side eligibility beyond the native
+ five-unit start check. Keep inferred policies explicit in the protocol ledger.
- [ ] Combine one tradeskill recipe. Check: valid ingredients and skills produce
the expected result QL; failure preserves the applicable inputs.
- [ ] Add one implant-building recipe. Check: the chosen cluster/implant pair
diff --git a/docs/player-trading.md b/docs/player-trading.md
@@ -1,9 +1,11 @@
# Original player trading contract
-Two-player trading is not implemented yet. The original 14.9.1 client has enough
-recovered protocol to open, cancel and confirm trades, but remote stack quantity
-delivery remains unresolved. Do not mark a transfer complete using a peer row
-that silently changes a stack to one charge.
+Two-player trading supports ordinary items, charged stacks, filled backpacks,
+free gifts and credits through the native trade windows. Both players consent
+before one SQLite transaction transfers ownership and cash. Cancellation keeps
+ownership and restores the native first-free layout. The server uses original
+client operations; the composed remote-template delivery sequence is a tested
+reconstruction, not a recovered historical server implementation.
Research is retained in `local/player-trade-research/native/README.md` and its
exported KKR/DDR/EER evidence. The shipped help file
@@ -56,19 +58,25 @@ returned row can collide with another offer's saved source slot. Draft source
snapshots must follow these reservations. Preserve IDs, counts, QL, ammunition
and container contents; cancellation changes placement, not ownership.
-DDR Accept handler 0x10048870 sends Cash6 before Accept1 even if cash is
-unchanged. It sets a one-shot flag reset by TradeStart. Incoming Accept invokes
+Enter commits the cash field locally through DDR SetCashMessage 0x10049410
+and parser 0x10049090; it does not transmit Cash6. DDR Accept handler
+0x10048870 sends Cash6 before Accept1 even if cash is unchanged. It sets a one-shot flag reset by TradeStart. Incoming Accept invokes
the local callback; DDR 0x10048e70 lights the opponent's green lamp.
No Unaccept action or second confirmation stage was recovered. Actions 7/8
are peer item operations. A later 2009 forum report of a confirmation dialog
does not establish that behavior in 14.9.1.
-Proposed server policy: freeze both baskets and cash after either acceptance;
-allow unchanged Cash6, but require cancellation before actual changes. Merely
-clearing server acceptance cannot make this UI send another Accept. The
-protocol has no basket revision or session nonce.
+The accepted player's offer is fixed. Once either player accepts, the other
+player may add items or increase cash, improving the terms already accepted.
+Removing items is rejected; reducing cash cancels the trade. This permits the
+native Cash6-on-Accept sequence without silently approving a worse basket.
+Simply clearing acceptance cannot make the one-shot UI send Accept again.
+This monotonic consent rule is server policy inferred from the native contract;
+the historical server's exact policy remains unproven. The protocol has no
+basket revision or session nonce. Source details and the superseded blanket
+freeze recommendation are in `local/player-trade-research/native/cash-consent.md`.
-## Restrictions and remaining quantity work
+## Restrictions and peer rows
The original start producer 0x1001f840 requires a different SimpleChar target
within five units. No faction restriction was recovered. Offering equipped
@@ -86,16 +94,59 @@ Complete preserves that row's count; its 0x1002dd90 call sets a dirty flag,
not quantity. Consequently a full item dynel plus Add7 is insufficient for
the correct displayed count of a charged template stack.
-InventoryUpdate's SimpleChar branch 0x10062ec0 accepts overflow page 110,
-not TradeInv. FullCharacter can seed remote ordinary rows, but also reapplies
-other character state; seeding followed by Add4 remains an untested delivery
-reconstruction. Completing both directions then rebuilding ordinary stacks
-could correct final inventory counts, but would leave inaccurate quantities
-in the basket before consent. Recover or verify a complete path before enabling
-stack trading.
-
-Server implementation still needs atomic two-player item/cash persistence,
-capacity and Unique checks against prospective inventories, filled-bag
-ownership, conflicting-action exclusion, current-session/range/death checks,
-and cancellation on disconnect, replacement or zoning. Tests must cover both
-native views and durable ownership through failure, replay and cold restart.
+For template rows, the server instead sends AddTemplate key `0x052e2f0c`
+with the offering player's outer identity and the low/high templates, QL and
+full count. KKR receiver 0x1007d090 supports a remote SimpleChar; helper
+0x1005ef90 creates its first-free ordinary row. Trade4 on that same actor moves
+the whole counted row into TradeInv. Native page208 displays the correct count,
+and Complete transfers it intact into the recipient's ordinary inventory.
+Portable backpacks use their actual ChestFullUpdate plus peer Add7; those roots
+have count one and retain a usable container identity.
+
+The template mirror has a temporary null native instance ID, as ordinary
+AddTemplate grants do. The server never allocates a replacement item: persistent
+IDs, QL, charges, ammunition and bag children travel unchanged. Cold reconnect
+restores native rows from those same persistent IDs.
+
+Template peer removal uses Trade5 on the offering actor, then CharacterAction112
+clears its restored remote ordinary scratch row. Abort restores all peer rows,
+so cleanup clears the same number of ordinary slots from64. Complete also fills
+the remote actor's ordinary inventory with outgoing local offers; those mirrors
+are cleared afterward. Local owned rows are preserved. Without cleanup,
+repeated sessions could fill invisible remote inventory and stop completion.
+Evidence: `local/player-trade-research/native/remote-template-delivery.md`.
+
+## Persistence, lifecycle and verification
+
+Each draft is shared by the exact two client sessions. Offered roots stay
+owned until commitment and are unavailable to conflicting item use, reload,
+shop/bank, loot and reclaim operations. An inventory move/delete/split cancels
+the draft before the original request can act on a newly restored slot.
+Departure, replacement, control edits, zoning, death or leaving the five-unit
+range cancel the draft. Every request also revalidates both participants.
+
+Completion rechecks exact offered rows and restrictions, removes all outgoing
+roots from detached candidate inventories, then allocates incoming items in
+TradeInv order. Capacity and Unique checks use these prospective inventories,
+so a full inventory can swap items and outgoing Unique roots free eligibility.
+Unique checks use carried/worn items and carried bag contents, matching current
+inventory acquisition policy; exact historical bank/reclaim inclusion remains
+unproven. Filled bags may not contain NoDrop or Unique children.
+
+Both players' placements and credit metadata commit in one existing SQLite
+transaction. Failed persistence publishes neither side or completion packet.
+After commitment, a failed reply disconnects/resynchronizes the affected client;
+it cannot reverse or repeat ownership. Both native Complete directions precede
+absolute local cash correction. No new item identity is allocated by a trade.
+
+Tests cover admission, malformed ownership/pages, cash bounds/overflow,
+consent, capacity swaps, Unique duplicates/swaps, bag contents, loaded weapons,
+failed first/second persistence, cancellation retry, conflicting actions,
+movement/control edits, death/reclaim, concurrent acceptance and lost replies.
+The actual two-client GPU WASM captures are in
+`local/player-trade-live-smoke/`. They verify both 25/50-charge baskets, a
+500/200-credit exchange, empty and filled backpack gifts, NoDrop and duplicate
+Unique rejection, disconnect cancellation and 32 offer/cancel cycles without
+remote-row accumulation. Cold restart verifies durable identities, quantities,
+balances and backpack contents. The clients use ordinary mouse/keyboard input;
+heap and SQLite probes only inspect the resulting state.
diff --git a/server/backpacks.go b/server/backpacks.go
@@ -75,6 +75,11 @@ func (server *server) handleOwnedItemUse(client *worldClient, body []byte) error
return nil
}
client.useSequence = sequence
+ if client.trade != nil {
+ reply := append([]byte(nil), body[16:]...)
+ binary.BigEndian.PutUint32(reply, 2)
+ return client.send(n3Packet(0x52526858, 50000, client.id, reply))
+ }
if page == 107 {
// Known carried contents remain usable after their bag window closes.
slot := binary.BigEndian.Uint32(body[44:48])
diff --git a/server/bank.go b/server/bank.go
@@ -91,7 +91,7 @@ func (server *server) handleBankUse(client *worldClient, body []byte) error {
terminal, exists := gamedata.BankTerminals[binary.BigEndian.Uint32(body[44:48])]
position := predictedPosition_locked(player, client, time.Now())
x, y, z := position[0]-terminal.Position[0], position[1]-terminal.Position[1], position[2]-terminal.Position[2]
- accepted := exists && player.playfield == terminal.Playfield && x*x+y*y+z*z <= 25 && client.equipment == nil
+ accepted := exists && player.playfield == terminal.Playfield && x*x+y*y+z*z <= 25 && client.equipment == nil && client.trade == nil
reply := append([]byte(nil), body[16:]...)
binary.BigEndian.PutUint32(reply, 2)
if accepted {
@@ -122,6 +122,9 @@ func (server *server) useRemoteBank_locked(client *worldClient, item ownedItem,
}
func (server *server) openBank_locked(client *worldClient) error {
+ if client.trade != nil {
+ return nil
+ }
player := server.characters[client.id]
if client.shop != nil {
if err := server.abortShop_locked(client); err != nil {
diff --git a/server/browser_account.go b/server/browser_account.go
@@ -208,6 +208,7 @@ func (server *server) browserAccount(w http.ResponseWriter, r *http.Request) {
}
for _, client := range server.clients {
if client.id == id || client.id == currentID {
+ server.cancelPlayerTrade_locked(client)
client.ready = false
if client.stream == nil {
client.disconnect(client.conn)
diff --git a/server/combat.go b/server/combat.go
@@ -470,6 +470,7 @@ func (server *server) finishDamageEffects_locked(attacker, target *character, pr
if target.health == 0 {
if !target.npc {
client := server.clients[target.id]
+ server.cancelPlayerTrade_locked(client)
target.position = predictedPosition_locked(&previous, client, now)
client.forward = 0
client.reclaimItems = nil
diff --git a/server/control.go b/server/control.go
@@ -335,6 +335,7 @@ func (server *server) applyUser_locked(character, updated *character) error {
updated.fighting = 0
updated.nextAttack = time.Time{}
*character = *updated
+ server.cancelPlayerTrade_locked(server.clients[character.id])
// Team side is derived from the durable roster and each member's affiliation.
if character.team != nil && previousSide != character.appearance>>9&3 {
for _, member := range character.team.members {
diff --git a/server/inventory.go b/server/inventory.go
@@ -201,6 +201,18 @@ 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.trade != nil {
+ if err := server.abortPlayerTrade_locked(client); err != nil {
+ return err
+ }
+ if key == 0x5e477770 && binary.BigEndian.Uint32(body[16:20]) == 52 {
+ return server.syncStacks_locked(client)
+ }
+ if key == 0x47537a24 {
+ return client.send(characterActionPacket(client.id, [5]uint32{146, binary.BigEndian.Uint32(body[16:20]), binary.BigEndian.Uint32(body[20:24])}))
+ }
+ return nil
+ }
if client.shop != nil {
if err := server.abortShop_locked(client); err != nil {
return err
diff --git a/server/item_database.go b/server/item_database.go
@@ -3,6 +3,7 @@ package main
import (
"database/sql"
"fmt"
+ "slices"
"strings"
"time"
)
@@ -47,7 +48,7 @@ func (server *server) persistItems_locked(store itemStore) error {
if store.edited != nil && store.edited.id == id {
player = *store.edited
}
- if store.flush || id == store.inventoryPlayer {
+ if store.flush || slices.Contains(store.inventoryPlayers, id) {
if err := insertPlayer(tx, &player); err != nil {
return err
}
@@ -61,8 +62,8 @@ func (server *server) persistItems_locked(store itemStore) error {
return err
}
}
- // Save metadata for the acting player; full snapshots include every player.
- if !store.flush && id != store.inventoryPlayer {
+ // Save metadata for the acting players; full snapshots include every player.
+ if !store.flush && !slices.Contains(store.inventoryPlayers, id) {
continue
}
if _, err := tx.Exec(`UPDATE players SET credits=?1, map_options=?2, map_area_1=?3, map_area_2=?4
diff --git a/server/item_store.go b/server/item_store.go
@@ -45,16 +45,16 @@ type playerVitalUpdate struct {
}
type itemStore struct {
- LastID uint32 `yaml:"last_id"`
- Items map[uint32]itemRecord `yaml:"items"`
- Players map[uint32]characterItemReferences `yaml:"players"`
- Corpses map[uint32][]ownedItem
- edited *character
- vitalUpdate *playerVitalUpdate
- skillLock *skillLockUpdate
- inventoryPlayer uint32
- checkpointAt time.Time
- flush bool
+ LastID uint32 `yaml:"last_id"`
+ Items map[uint32]itemRecord `yaml:"items"`
+ Players map[uint32]characterItemReferences `yaml:"players"`
+ Corpses map[uint32][]ownedItem
+ edited *character
+ vitalUpdate *playerVitalUpdate
+ skillLock *skillLockUpdate
+ inventoryPlayers []uint32
+ checkpointAt time.Time
+ flush bool
}
func emptyItemSlots(count uint32) map[string]*uint32 {
@@ -188,7 +188,7 @@ func reclaimItems(entries []reclaimItem) []ownedItem {
func (server *server) itemStore_locked(character *character, inventory playerInventory) (itemStore, error) {
store := itemStore{LastID: max(server.nextItem, inventory.LastID), Items: maps.Clone(server.items),
- Players: make(map[uint32]characterItemReferences), Corpses: make(map[uint32][]ownedItem), inventoryPlayer: character.id}
+ Players: make(map[uint32]characterItemReferences), Corpses: make(map[uint32][]ownedItem), inventoryPlayers: []uint32{character.id}}
if store.Items == nil {
store.Items = make(map[uint32]itemRecord)
}
diff --git a/server/loot.go b/server/loot.go
@@ -132,7 +132,7 @@ func (server *server) handleLootUse(client *worldClient, body []byte) error {
corpse := server.characters[binary.BigEndian.Uint32(body[44:48])]
reply := append([]byte(nil), body[16:]...)
binary.BigEndian.PutUint32(reply, 2)
- if !server.canLoot_locked(client, corpse) {
+ if client.trade != nil || !server.canLoot_locked(client, corpse) {
return client.send(n3Packet(0x52526858, 50000, client.id, reply))
}
diff --git a/server/main.go b/server/main.go
@@ -270,6 +270,7 @@ func (server *server) serveWorldClient(client *worldClient) error {
server.mutex.Unlock()
return
}
+ server.cancelPlayerTrade_locked(client)
client.ready = false
updates := make(map[*worldClient][][]byte)
server.cancelCombat_locked(character.id, updates)
@@ -333,6 +334,7 @@ func (server *server) serveWorldClient(client *worldClient) error {
replaceActor := false
if previous := server.clients[character.id]; previous != nil {
replaceActor = previous.ready
+ server.cancelPlayerTrade_locked(previous)
previous.ready = false
server.cancelCombat_locked(character.id, combatUpdates)
if previous.stream != nil {
@@ -480,7 +482,7 @@ func (server *server) serveWorldClient(client *worldClient) error {
return err
}
case 0x36284f6e:
- if err := server.handleShopTrade(client, body); err != nil {
+ if err := server.handleTrade(client, body); err != nil {
return err
}
case 0x51492120:
diff --git a/server/map_purchases_test.go b/server/map_purchases_test.go
@@ -75,13 +75,13 @@ func TestMapPurchaseDeliversAllFiveUpgradesThenUploadsExactlyOnce(t *testing.T)
world, conn := newMapPurchaseWorld(t)
client, player := world.clients[1], world.characters[1]
for _, index := range []uint32{4, 0, 1, 2, 3, 4} {
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221685407}, [2]uint32{111, index})[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221685407}, [2]uint32{111, index})[20:]); err != nil {
t.Fatal(err)
}
}
conn.packets = nil
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
purchased := newTestInventoryServer(t).characters[1].inventory
if err != nil || purchased.Credits != 48119 || len(purchased.Items) != 7 || world.nextItem != 7 || len(conn.packets) != 8 {
@@ -130,7 +130,7 @@ func TestMapPurchaseDoesNotApplyUploadSkillRequirementsAtCheckout(t *testing.T)
shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221685407}, [2]uint32{111, 4})[20:],
shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:],
} {
- if err := world.handleShopTrade(client, request); err != nil {
+ if err := world.handleTrade(client, request); err != nil {
t.Fatal(err)
}
}
@@ -147,7 +147,7 @@ func TestMapPurchaseRollbackKeepsBasketRetryableWithoutPartialOwnership(t *testi
world, conn := newMapPurchaseWorld(t)
client, player := world.clients[1], world.characters[1]
for _, index := range []uint32{3, 4} {
- world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221685407}, [2]uint32{111, index})[20:])
+ world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221685407}, [2]uint32{111, index})[20:])
}
if _, err := world.db.Exec("CREATE TRIGGER reject_map BEFORE INSERT ON items WHEN NEW.id=3 BEGIN SELECT RAISE(FAIL, 'second map'); END"); err != nil {
t.Fatal(err)
@@ -155,7 +155,7 @@ func TestMapPurchaseRollbackKeepsBasketRetryableWithoutPartialOwnership(t *testi
conn.packets = nil
accept := shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]
- failed := world.handleShopTrade(client, accept)
+ failed := world.handleTrade(client, accept)
rejected := newTestInventoryServer(t).characters[1].inventory
if failed == nil || rejected.Credits != 100000 || len(rejected.Items) != 1 || !reflect.DeepEqual(rejected, player.inventory) || world.nextItem != 1 || len(conn.packets) != 0 || client.shop == nil {
@@ -165,7 +165,7 @@ func TestMapPurchaseRollbackKeepsBasketRetryableWithoutPartialOwnership(t *testi
t.Fatal(err)
}
- err := world.handleShopTrade(client, accept)
+ err := world.handleTrade(client, accept)
restored := newTestInventoryServer(t).characters[1].inventory
if err != nil || restored.Credits != 98464 || len(restored.Items) != 3 || restored.Items[1].ID != 2 || restored.Items[2].ID != 3 || restored.Items[1].Template != 116692 || restored.Items[2].Template != 116694 || world.nextItem != 3 {
@@ -179,7 +179,7 @@ func TestMapPurchaseRejectedOrAbandonedBasketPreservesCashAndItems(t *testing.T)
world, _ := newMapPurchaseWorld(t)
client, player := world.clients[1], world.characters[1]
add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221685407}, [2]uint32{111, 4})[20:]
- if err := world.handleShopTrade(client, add); err != nil {
+ if err := world.handleTrade(client, add); err != nil {
t.Fatal(err)
}
request := shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]
@@ -194,7 +194,7 @@ func TestMapPurchaseRejectedOrAbandonedBasketPreservesCashAndItems(t *testing.T)
case "cancel":
request = shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]
case "remove":
- world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{51035, 3221685407}, [2]uint32{111, 4})[20:])
+ world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{51035, 3221685407}, [2]uint32{111, 4})[20:])
case "unknown row":
request = shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221685407}, [2]uint32{111, 5})[20:]
}
@@ -205,7 +205,7 @@ func TestMapPurchaseRejectedOrAbandonedBasketPreservesCashAndItems(t *testing.T)
before.Items = slices.Clone(before.Items)
next := world.nextItem
- err := world.handleShopTrade(client, request)
+ err := world.handleTrade(client, request)
restored := newTestInventoryServer(t).characters[1].inventory
if err != nil || client.shop != nil || !reflect.DeepEqual(restored, before) || !reflect.DeepEqual(player.inventory, before) || world.nextItem != next {
diff --git a/server/player_trading.go b/server/player_trading.go
@@ -0,0 +1,350 @@
+package main
+
+import (
+ "cmp"
+ "encoding/binary"
+ "log"
+ "maps"
+ "slices"
+ "time"
+)
+
+type playerTrade struct {
+ clients [2]*worldClient
+ items [2]map[uint32]ownedItem
+ cash [2]uint32
+ accepted [2]bool
+}
+
+func (server *server) playerTradeAvailable_locked(first, second *worldClient) bool {
+ if first == nil || second == nil || first == second {
+ return false
+ }
+ for _, client := range []*worldClient{first, second} {
+ if !client.target || server.clients[client.id] != client || !client.ready || client.loading || client.equipment != nil || client.shop != nil ||
+ server.characters[client.id].health == 0 {
+ return false
+ }
+ }
+ a, b := server.characters[first.id], server.characters[second.id]
+ if a.playfield != b.playfield {
+ return false
+ }
+ now := time.Now()
+ x, y := predictedPosition_locked(a, first, now), predictedPosition_locked(b, second, now)
+ dx, dy, dz := x[0]-y[0], x[1]-y[1], x[2]-y[2]
+ return dx*dx+dy*dy+dz*dz <= 25
+}
+
+func tradeSlots(items map[uint32]ownedItem) []uint32 {
+ slots := make([]uint32, 0, len(items))
+ for slot := range items {
+ slots = append(slots, slot)
+ }
+ slices.Sort(slots)
+ return slots
+}
+
+func (server *server) savePlayerTrade_locked(trade *playerTrade, inventories [2]playerInventory) error {
+ store, err := server.itemStore_locked(&character{}, playerInventory{})
+ if err != nil {
+ return err
+ }
+ store.inventoryPlayers = []uint32{trade.clients[0].id, trade.clients[1].id}
+ for side, client := range trade.clients {
+ slices.SortFunc(inventories[side].Items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) })
+ inventories[side].LastID = store.LastID
+ if err := inventories[side].validate(); err != nil {
+ return err
+ }
+ store.Players[client.id] = inventories[side].references()
+ }
+ if err := server.writeItemStore_locked(store); err != nil {
+ return err
+ }
+ for side, client := range trade.clients {
+ server.characters[client.id].inventory = inventories[side]
+ }
+ return nil
+}
+
+func clearPeerTradeRows(client *worldClient, owner uint32, count int) error {
+ // Remote ordinary rows are temporary mirrors. Each prior Add moved its
+ // scratch row into TradeInv, so restoration/completion starts at slot64.
+ for offset := range count {
+ if err := client.send(characterActionPacket(owner, [5]uint32{112, 104, 64 + uint32(offset)})); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func (server *server) abortPlayerTrade_locked(client *worldClient) error {
+ trade := client.trade
+ if trade == nil {
+ return nil
+ }
+ var inventories [2]playerInventory
+ for side, participant := range trade.clients {
+ inventories[side], _ = restoredTradeInventory(server.characters[participant.id].inventory, trade.items[side], tradeSlots(trade.items[side]))
+ }
+ if err := server.savePlayerTrade_locked(trade, inventories); err != nil {
+ return err
+ }
+ for _, participant := range trade.clients {
+ participant.trade = nil
+ }
+ for side, participant := range trade.clients {
+ if err := participant.send(shopTradePacket([2]uint32{50000, client.id}, 2, [2]uint32{}, [2]uint32{})); err != nil {
+ participant.disconnect(participant.conn)
+ continue
+ }
+ if err := clearPeerTradeRows(participant, trade.clients[1-side].id, len(trade.items[1-side])); err != nil {
+ participant.disconnect(participant.conn)
+ }
+ }
+ return nil
+}
+
+func (server *server) cancelPlayerTrade_locked(client *worldClient) {
+ if client == nil || client.trade == nil {
+ return
+ }
+ trade := client.trade
+ if err := server.abortPlayerTrade_locked(client); err != nil {
+ // A departing or replaced session cannot keep a retryable UI. Ownership
+ // never left either player; reconnect recovers the last durable layout.
+ log.Printf("Cancelling player trade: %v", err)
+ for _, participant := range trade.clients {
+ participant.trade = nil
+ participant.disconnect(participant.conn)
+ }
+ }
+}
+
+func tradeableItem(inventory playerInventory, item ownedItem) bool {
+ if itemStat(item.templateDefinition(), 0)&0x04000000 != 0 {
+ return false
+ }
+ for _, child := range inventory.Containers[item.ID] {
+ if itemStat(child.templateDefinition(), 0)&0x0c000000 != 0 {
+ return false
+ }
+ }
+ return true
+}
+
+func (server *server) handlePlayerTrade_locked(client *worldClient, body []byte) error {
+ action := binary.BigEndian.Uint32(body[20:24])
+ 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 == 0 {
+ if client.trade != nil {
+ return server.abortPlayerTrade_locked(client)
+ }
+ peer := server.clients[first[1]]
+ if first[0] != 50000 || second != [2]uint32{} || !server.playerTradeAvailable_locked(client, peer) || peer.trade != nil {
+ return nil
+ }
+ trade := &playerTrade{clients: [2]*worldClient{client, peer}, items: [2]map[uint32]ownedItem{{}, {}}}
+ client.trade, peer.trade = trade, trade
+ for _, participant := range trade.clients {
+ participant.bank = nil
+ if err := participant.send(shopTradePacket([2]uint32{50000, client.id}, 0, first, second)); err != nil {
+ server.cancelPlayerTrade_locked(client)
+ return err
+ }
+ }
+ return nil
+ }
+ trade := client.trade
+ if action == 2 || !server.playerTradeAvailable_locked(trade.clients[0], trade.clients[1]) {
+ return server.abortPlayerTrade_locked(client)
+ }
+ side := 0
+ if trade.clients[0] != client {
+ side = 1
+ }
+ peer := trade.clients[1-side]
+ player := server.characters[client.id]
+ owner := [2]uint32{50000, client.id}
+ switch action {
+ case 4:
+ if trade.accepted[side] {
+ return nil
+ }
+ if first != owner || second[0] != 104 || second[1] < 64 || second[1] >= 94 {
+ return server.abortPlayerTrade_locked(client)
+ }
+ index := slices.IndexFunc(player.inventory.Items, func(item ownedItem) bool { return item.Slot == second[1] })
+ if index < 0 || !tradeableItem(player.inventory, player.inventory.Items[index]) {
+ return server.abortPlayerTrade_locked(client)
+ }
+ item := player.inventory.Items[index]
+ for _, offered := range trade.items[side] {
+ if offered.ID == item.ID {
+ return nil
+ }
+ }
+ var slot uint32
+ for _, exists := trade.items[side][slot]; exists; _, exists = trade.items[side][slot] {
+ slot++
+ }
+ if slot == 30 {
+ return server.abortPlayerTrade_locked(client)
+ }
+ trade.items[side][slot] = item
+ if err := client.send(shopTradePacket(owner, 4, first, second)); err != nil {
+ return err
+ }
+ if item.isPortableContainer() {
+ for handle, bag := range client.backpacks {
+ if bag.id == item.ID {
+ if bag.open {
+ if err := client.send(backpackClosePacket(client.id, item.ID)); err != nil {
+ return err
+ }
+ }
+ delete(client.backpacks, handle)
+ }
+ }
+ if err := peer.send(backpackPacket(client.id, player.playfield, item, 104)); err != nil {
+ return err
+ }
+ return peer.send(shopTradePacket([2]uint32{50000, peer.id}, 7, owner, [2]uint32{item.Type, item.ID}))
+ }
+ // AddTemplate's receiver supports remote actors. Move the counted scratch
+ // row intact; Add7 would construct a peer row with quantity one.
+ low, high := item.templateIDs()
+ var seed []byte
+ for _, value := range []uint32{low, high, item.Quality, uint32(item.Count)} {
+ seed = binary.BigEndian.AppendUint32(seed, value)
+ }
+ if err := peer.send(n3Packet(0x052e2f0c, 50000, client.id, seed)); err != nil {
+ return err
+ }
+ return peer.send(shopTradePacket(owner, 4, owner, [2]uint32{104, 64}))
+ case 5:
+ if trade.accepted[0] || trade.accepted[1] {
+ return nil
+ }
+ item, exists := trade.items[side][second[1]]
+ if first != owner || second[0] != 108 || !exists {
+ return server.abortPlayerTrade_locked(client)
+ }
+ if err := server.restoreTradeItems_locked(client, trade.items[side], []uint32{second[1]}); err != nil {
+ return err
+ }
+ if err := client.send(shopTradePacket(owner, 5, owner, second)); err != nil {
+ return err
+ }
+ if item.isPortableContainer() {
+ return peer.send(shopTradePacket([2]uint32{50000, peer.id}, 8, owner, [2]uint32{item.Type, item.ID}))
+ }
+ if err := peer.send(shopTradePacket(owner, 5, owner, second)); err != nil {
+ return err
+ }
+ return clearPeerTradeRows(peer, client.id, 1)
+ case 6:
+ if first[0] != 0 || second != [2]uint32{} || first[1] > player.inventory.Credits || first[1] > 1000000000 {
+ return server.abortPlayerTrade_locked(client)
+ }
+ // The unaccepted player may improve the terms their peer accepted.
+ if (trade.accepted[side] && first[1] != trade.cash[side]) || (trade.accepted[1-side] && first[1] < trade.cash[side]) {
+ return server.abortPlayerTrade_locked(client)
+ }
+ trade.cash[side] = first[1]
+ for _, participant := range trade.clients {
+ if err := participant.send(shopTradePacket(owner, 6, first, second)); err != nil {
+ return err
+ }
+ }
+ return nil
+ case 1:
+ if first != [2]uint32{} || second != [2]uint32{} {
+ return server.abortPlayerTrade_locked(client)
+ }
+ if trade.accepted[side] {
+ return nil
+ }
+ if !trade.accepted[1-side] {
+ trade.accepted[side] = true
+ return peer.send(shopTradePacket([2]uint32{50000, peer.id}, 1, first, second))
+ }
+ return server.completePlayerTrade_locked(client)
+ }
+ return server.abortPlayerTrade_locked(client)
+}
+
+func (server *server) completePlayerTrade_locked(client *worldClient) error {
+ trade := client.trade
+ var inventories [2]playerInventory
+ for side, participant := range trade.clients {
+ inventory := server.characters[participant.id].inventory
+ inventory.Items = slices.Clone(inventory.Items)
+ inventory.Containers = maps.Clone(inventory.Containers)
+ for _, item := range trade.items[side] {
+ index := slices.Index(inventory.Items, item)
+ if index < 0 || !tradeableItem(inventory, item) {
+ return server.abortPlayerTrade_locked(client)
+ }
+ inventory.Items = slices.Delete(inventory.Items, index, index+1)
+ delete(inventory.Containers, item.ID)
+ }
+ if trade.cash[side] > inventory.Credits {
+ return server.abortPlayerTrade_locked(client)
+ }
+ balance := uint64(inventory.Credits-trade.cash[side]) + uint64(trade.cash[1-side])
+ if balance > 1000000000 {
+ return server.abortPlayerTrade_locked(client)
+ }
+ inventory.Credits = uint32(balance)
+ inventories[side] = inventory
+ }
+ for side := range inventories {
+ for _, slot := range tradeSlots(trade.items[1-side]) {
+ item := trade.items[1-side][slot]
+ if itemStat(item.templateDefinition(), 0)&0x08000000 != 0 && inventories[side].carriesUnique(item) {
+ return server.abortPlayerTrade_locked(client)
+ }
+ item.Slot = 64
+ for slices.ContainsFunc(inventories[side].Items, func(other ownedItem) bool { return other.Slot == item.Slot }) {
+ item.Slot++
+ }
+ if item.Slot >= 94 {
+ return server.abortPlayerTrade_locked(client)
+ }
+ inventories[side].Items = append(inventories[side].Items, item)
+ contents := server.characters[trade.clients[1-side].id].inventory.Containers[item.ID]
+ if len(contents) != 0 {
+ if inventories[side].Containers == nil {
+ inventories[side].Containers = make(map[uint32][]ownedItem)
+ }
+ inventories[side].Containers[item.ID] = slices.Clone(contents)
+ }
+ }
+ }
+ if err := server.savePlayerTrade_locked(trade, inventories); err != nil {
+ return err
+ }
+ for _, participant := range trade.clients {
+ participant.trade = nil
+ }
+ for side, participant := range trade.clients {
+ for _, owner := range trade.clients {
+ if err := participant.send(shopTradePacket([2]uint32{50000, owner.id}, 3, [2]uint32{}, [2]uint32{})); err != nil {
+ participant.disconnect(participant.conn)
+ break
+ }
+ }
+ if err := clearPeerTradeRows(participant, trade.clients[1-side].id, len(trade.items[side])); err != nil {
+ participant.disconnect(participant.conn)
+ }
+ stats := binary.BigEndian.AppendUint32(nil, 61)
+ stats = binary.BigEndian.AppendUint32(stats, inventories[side].Credits)
+ if err := participant.send(n3Packet(0x2b333d6e, 50000, participant.id, stats)); err != nil {
+ participant.disconnect(participant.conn)
+ }
+ }
+ return nil
+}
diff --git a/server/player_trading_lifecycle_test.go b/server/player_trading_lifecycle_test.go
@@ -0,0 +1,206 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "reflect"
+ "sync"
+ "testing"
+)
+
+func TestPlayerTradeCancellationRestoresBothOwnersAtomically(t *testing.T) {
+ world, conns := newPlayerTradeWorld(t)
+ for _, id := range []uint32{1, 2} {
+ inventory := world.characters[id].inventory
+ inventory.Items[len(inventory.Items)-1].Slot = 70
+ if err := world.saveInventory_locked(world.characters[id], inventory); err != nil {
+ t.Fatal(err)
+ }
+ }
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 70})
+ playerTradeRequest(t, world, 2, 4, [2]uint32{50000, 2}, [2]uint32{104, 70})
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("CREATE TRIGGER fail_abort BEFORE INSERT ON item_locations WHEN NEW.item_id=3 BEGIN SELECT RAISE(ABORT, 'second restore'); END"); err != nil {
+ t.Fatal(err)
+ }
+ conns[0].packets, conns[1].packets = nil, nil
+ request := shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{0, 1}, [2]uint32{})[20:]
+
+ failed := world.handleTrade(world.clients[1], request)
+ after, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if failed == nil || !bytes.Equal(before, after) || world.clients[1].trade == nil || world.clients[2].trade == nil ||
+ world.clients[1].trade.items[0][0].Slot != 70 || world.clients[2].trade.items[1][0].Slot != 70 ||
+ len(conns[0].packets) != 0 || len(conns[1].packets) != 0 {
+ t.Fatal("failed second restoration partially published cancellation")
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_abort"); err != nil {
+ t.Fatal(err)
+ }
+ playerTradeRequest(t, world, 1, 2, [2]uint32{0, 1}, [2]uint32{})
+ restored := newTestInventoryServer(t)
+ if restored.characters[1].inventory.Items[1].Slot != 65 || restored.characters[2].inventory.Items[0].Slot != 64 ||
+ world.clients[1].trade != nil || world.clients[2].trade != nil {
+ t.Fatal("cancellation retry did not restore both layouts")
+ }
+ for _, conn := range conns {
+ if len(conn.packets) != 2 || binary.BigEndian.Uint32(conn.packets[0][33:37]) != 2 ||
+ binary.BigEndian.Uint32(conn.packets[1][29:33]) != 112 {
+ t.Fatal("cancellation did not clear the peer's restored scratch row")
+ }
+ }
+}
+
+func TestPlayerTradeConflictingInventoryActionCancelsWithoutActingOnRestoredSlots(t *testing.T) {
+ world, _ := newPlayerTradeWorld(t)
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+ before := world.characters[1].inventory
+ before.LastID = 3
+
+ if err := world.handleInventory(world.clients[1], inventoryDeletePacket(1, 64)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+
+ if world.clients[1].trade != nil || world.clients[2].trade != nil || !reflect.DeepEqual(before, world.characters[1].inventory) ||
+ !reflect.DeepEqual(before, newTestInventoryServer(t).characters[1].inventory) {
+ t.Fatal("conflicting delete consumed a just-restored offer")
+ }
+}
+
+func TestPlayerTradeMovementAndControlEditCancelTheDraft(t *testing.T) {
+ for _, scenario := range []string{"movement", "edit"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newPlayerTradeWorld(t)
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 4, [2]uint32{50000, 2}, [2]uint32{104, 64})
+
+ if scenario == "movement" {
+ moved := *world.characters[1]
+ moved.position[0] = 20
+ request := npcMovementPacket(&moved, 2)[20:]
+ request = append(request[:16:16], encodeMovement1491(request[16:])...)
+ if err := world.handleMovement(world.clients[1], request); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ updated := *world.characters[1]
+ updated.name = "Renamed Owner"
+ world.updateMutex.Lock()
+ if err := world.updateUser_locked(updated.userData()); err != nil {
+ t.Fatal(err)
+ }
+ world.updateMutex.Unlock()
+ }
+
+ if world.clients[2].trade != nil || world.characters[2].inventory.Items[0].ID != 3 ||
+ world.characters[1].inventory.Credits != 20000 || world.characters[2].inventory.Credits != 10000 {
+ t.Fatal("departing or edited player left a peer draft or transferred value")
+ }
+ })
+ }
+}
+
+func TestPlayerTradeConcurrentAcceptsCommitOnce(t *testing.T) {
+ world, _ := newPlayerTradeWorld(t)
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+ playerTradeRequest(t, world, 1, 6, [2]uint32{0, 100}, [2]uint32{})
+ var wait sync.WaitGroup
+ errors := make(chan error, 2)
+
+ for _, id := range []uint32{1, 2} {
+ wait.Add(1)
+ go func() {
+ defer wait.Done()
+ errors <- world.handleTrade(world.clients[id], shopTradePacket([2]uint32{50000, id}, 1, [2]uint32{}, [2]uint32{})[20:])
+ }()
+ }
+ wait.Wait()
+ close(errors)
+ for err := range errors {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ restored := newTestInventoryServer(t)
+
+ if restored.characters[1].inventory.Credits != 19900 || restored.characters[2].inventory.Credits != 10100 ||
+ len(restored.characters[1].inventory.Items) != 1 || len(restored.characters[2].inventory.Items) != 2 ||
+ world.clients[1].trade != nil || world.clients[2].trade != nil {
+ t.Fatal("concurrent acceptance lost or repeated value")
+ }
+}
+
+func TestPlayerTradeLostCompletionReplyKeepsCommittedOwnership(t *testing.T) {
+ world, _ := newPlayerTradeWorld(t)
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+ playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{})
+ world.clients[1].conn = &failingCombatConn{}
+
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ restored := newTestInventoryServer(t)
+
+ if len(restored.characters[1].inventory.Items) != 1 || len(restored.characters[2].inventory.Items) != 2 ||
+ restored.characters[2].inventory.Items[0].ID != 2 || restored.characters[2].inventory.Items[0].Count != 25 ||
+ world.clients[1].trade != nil || world.clients[2].trade != nil {
+ t.Fatal("lost completion reversed or repeated committed ownership")
+ }
+}
+
+func TestPlayerTradeDeathReclaimsOnlyTheDeadOwnersItems(t *testing.T) {
+ world, _ := newPlayerTradeWorld(t)
+ world.characters[1].level = 10
+ if err := world.saveUser_locked(world.characters[1]); err != nil {
+ t.Fatal(err)
+ }
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+ playerTradeRequest(t, world, 2, 4, [2]uint32{50000, 2}, [2]uint32{104, 64})
+
+ defeatReclaimPlayer(t, world)
+ restored := newTestInventoryServer(t)
+
+ dead, living := restored.characters[1].inventory, restored.characters[2].inventory
+ if restored.characters[1].health != 0 || len(dead.Items) != 0 || len(dead.Reclaim) != 2 || dead.Reclaim[1].Item.ID != 2 || dead.Reclaim[1].Item.Count != 25 ||
+ len(living.Items) != 1 || living.Items[0].ID != 3 || living.Items[0].Count != 50 ||
+ world.clients[1].trade != nil || world.clients[2].trade != nil {
+ t.Fatal("death resurrected an offer or took the living peer's items")
+ }
+}
+
+func TestPlayerTradeOfferedResourceKitCannotBeConsumed(t *testing.T) {
+ world, conns := newPlayerTradeWorld(t)
+ player := world.characters[1]
+ player.nano = 0
+ player.stats.NanoAiding.FirstAid = 6
+ world.clients[1].selectedTarget = [2]uint32{50000, 1}
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+ conns[0].packets = nil
+
+ err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 65, 1)[20:])
+
+ if err != nil || player.nano != 0 || player.inventory.Items[1].Count != 25 || world.clients[1].trade == nil ||
+ len(conns[0].packets) != 1 || binary.BigEndian.Uint32(conns[0].packets[0][29:33]) != 2 {
+ t.Fatal("held kit was consumed or acknowledged as usable")
+ }
+ playerTradeRequest(t, world, 1, 2, [2]uint32{}, [2]uint32{})
+ if err := world.handleOwnedItemUse(world.clients[1], backpackUseRequest(1, 65, 2)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if player.inventory.Items[1].Count != 24 || player.nano == 0 {
+ t.Fatal("released fixture kit was not otherwise eligible for use")
+ }
+}
diff --git a/server/player_trading_rejection_test.go b/server/player_trading_rejection_test.go
@@ -0,0 +1,310 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "reflect"
+ "slices"
+ "testing"
+)
+
+func TestPlayerTradeRejectsForgedAndUnaffordableRequests(t *testing.T) {
+ for _, scenario := range []string{"foreign owner", "equipment", "wrong page", "missing", "negative cash", "unfunded cash", "cash cap", "complete request", "wrong subject", "wrong version"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newPlayerTradeWorld(t)
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ body := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})[20:]
+ switch scenario {
+ case "foreign owner":
+ binary.BigEndian.PutUint32(body[28:32], 2)
+ case "equipment":
+ binary.BigEndian.PutUint32(body[36:40], 6)
+ case "wrong page":
+ binary.BigEndian.PutUint32(body[32:36], 107)
+ case "missing":
+ binary.BigEndian.PutUint32(body[36:40], 93)
+ case "negative cash", "unfunded cash", "cash cap":
+ amount := uint32(0xffffffff)
+ if scenario == "unfunded cash" {
+ amount = 20001
+ }
+ if scenario == "cash cap" {
+ amount = 1000000001
+ }
+ body = shopTradePacket([2]uint32{50000, 1}, 6, [2]uint32{0, amount}, [2]uint32{})[20:]
+ case "complete request":
+ binary.BigEndian.PutUint32(body[20:24], 3)
+ case "wrong subject":
+ binary.BigEndian.PutUint32(body[8:12], 2)
+ case "wrong version":
+ binary.BigEndian.PutUint32(body[16:20], 2)
+ }
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if err := world.handleTrade(world.clients[1], body); err != nil {
+ t.Fatal(err)
+ }
+ after, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if !bytes.Equal(before, after) || world.characters[1].inventory.Credits != 20000 || world.characters[2].inventory.Credits != 10000 ||
+ world.clients[1].trade != nil && len(world.clients[1].trade.items[0]) != 0 {
+ t.Fatal("invalid request moved value or populated an offer")
+ }
+ })
+ }
+}
+
+func TestPlayerTradeFreezesConsentAndAcceptsUnchangedCash(t *testing.T) {
+ for _, scenario := range []string{"unchanged", "add", "remove", "decreased cash", "increased cash"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newPlayerTradeWorld(t)
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+ playerTradeRequest(t, world, 2, 6, [2]uint32{0, 100}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{})
+
+ switch scenario {
+ case "add":
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})
+ case "remove":
+ playerTradeRequest(t, world, 1, 5, [2]uint32{50000, 1}, [2]uint32{108, 0})
+ case "decreased cash":
+ playerTradeRequest(t, world, 2, 6, [2]uint32{0, 99}, [2]uint32{})
+ case "increased cash":
+ playerTradeRequest(t, world, 2, 6, [2]uint32{0, 101}, [2]uint32{})
+ }
+ if scenario != "increased cash" {
+ playerTradeRequest(t, world, 2, 6, [2]uint32{0, 100}, [2]uint32{})
+ }
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ restored := newTestInventoryServer(t)
+
+ first, second := restored.characters[1].inventory, restored.characters[2].inventory
+ if scenario == "decreased cash" {
+ if first.Credits != 20000 || second.Credits != 10000 || len(first.Items) != 2 || len(second.Items) != 1 {
+ t.Fatal("cash edit changed a consented trade")
+ }
+ return
+ }
+ if scenario == "increased cash" {
+ if first.Credits != 20101 || second.Credits != 9899 {
+ t.Fatal("improved offer was rejected after peer acceptance")
+ }
+ return
+ }
+ if first.Credits != 20100 || second.Credits != 9900 || len(first.Items) != 1 || len(second.Items) != 2 ||
+ second.Items[0].ID != 2 || second.Items[0].Count != 25 || second.Items[1].ID != 3 {
+ t.Fatal("frozen basket changed or native unchanged Cash6 prevented completion")
+ }
+ })
+ }
+}
+
+func TestPlayerTradeNativeCashSequenceAllowsImprovingTheUnacceptedOffer(t *testing.T) {
+ world, _ := newPlayerTradeWorld(t)
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+
+ playerTradeRequest(t, world, 1, 6, [2]uint32{0, 500}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 6, [2]uint32{0, 200}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 4, [2]uint32{50000, 2}, [2]uint32{104, 64})
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ restored := newTestInventoryServer(t)
+
+ if restored.characters[1].inventory.Credits != 19700 || restored.characters[2].inventory.Credits != 10300 ||
+ len(restored.characters[1].inventory.Items) != 2 || restored.characters[1].inventory.Items[1].ID != 3 ||
+ len(restored.characters[2].inventory.Items) != 1 || restored.characters[2].inventory.Items[0].ID != 2 {
+ t.Fatal("cash and items added by the unaccepted player failed to preserve the peer's consent")
+ }
+}
+
+func TestPlayerTradeCapacityAndUniqueUseProspectiveInventories(t *testing.T) {
+ for _, scenario := range []string{"full gift", "full swap", "duplicate unique", "unique swap", "cash overflow"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, _ := newPlayerTradeWorld(t)
+ if scenario == "full gift" || scenario == "full swap" {
+ for range 28 {
+ if granted, err := world.grantItem_locked(world.characters[1], 25820); err != nil || !granted {
+ t.Fatalf("fill: %v %v", granted, err)
+ }
+ }
+ }
+ if scenario == "duplicate unique" || scenario == "unique swap" {
+ for _, id := range []uint32{1, 2} {
+ if granted, err := world.grantItem_locked(world.characters[id], 161699); err != nil || !granted {
+ t.Fatalf("unique: %v %v", granted, err)
+ }
+ }
+ }
+ if scenario == "cash overflow" {
+ inventory := world.characters[1].inventory
+ inventory.Credits = 1000000000
+ if err := world.saveInventory_locked(world.characters[1], inventory); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ if scenario == "duplicate unique" || scenario == "unique swap" {
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 66})
+ if scenario == "unique swap" {
+ playerTradeRequest(t, world, 2, 4, [2]uint32{50000, 2}, [2]uint32{104, 65})
+ }
+ } else if scenario == "cash overflow" {
+ playerTradeRequest(t, world, 2, 6, [2]uint32{0, 1}, [2]uint32{})
+ } else {
+ playerTradeRequest(t, world, 2, 4, [2]uint32{50000, 2}, [2]uint32{104, 64})
+ if scenario == "full swap" {
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})
+ }
+ }
+
+ playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ after, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if world.clients[1].trade != nil || world.clients[2].trade != nil {
+ t.Fatal("trade remained active")
+ }
+ if scenario != "full swap" && scenario != "unique swap" {
+ if !bytes.Equal(before, after) {
+ t.Fatal("rejected capacity/Unique/cash outcome changed durable value")
+ }
+ return
+ }
+ if scenario == "full swap" {
+ if len(world.characters[1].inventory.Items) != 30 || world.characters[1].inventory.Items[1].ID != 3 ||
+ world.characters[2].inventory.Items[0].ID != 1 || world.characters[1].inventory.Items[1].Count != 50 {
+ t.Fatal("net-capacity swap was rejected or merged")
+ }
+ } else if !slices.ContainsFunc(world.characters[1].inventory.Items, func(item ownedItem) bool { return item.ID == 5 }) ||
+ !slices.ContainsFunc(world.characters[2].inventory.Items, func(item ownedItem) bool { return item.ID == 4 }) {
+ t.Fatal("outgoing Unique roots did not free duplicate eligibility")
+ }
+ })
+ }
+}
+
+func TestPlayerTradeBackpackContentsAndRestrictions(t *testing.T) {
+ for _, scenario := range []string{"ordinary contents", "NoDrop root", "NoDrop child", "Unique child"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, conns := newPlayerTradeWorld(t)
+ template := uint32(99228)
+ if scenario == "NoDrop root" {
+ template = 116648
+ }
+ if granted, err := world.grantItem_locked(world.characters[1], template); err != nil || !granted {
+ t.Fatalf("root: %v %v", granted, err)
+ }
+ if scenario != "NoDrop root" {
+ template = 85366
+ if scenario == "NoDrop child" {
+ template = 116648
+ }
+ if scenario == "Unique child" {
+ template = 161699
+ }
+ if granted, err := world.grantItem_locked(world.characters[1], template); err != nil || !granted {
+ t.Fatalf("child: %v %v", granted, err)
+ }
+ inventory := world.characters[1].inventory
+ inventory.Items = slices.Clone(inventory.Items)
+ child := inventory.Items[3]
+ child.Slot = 20
+ inventory.Items = inventory.Items[:3]
+ inventory.Containers = map[uint32][]ownedItem{4: {child}}
+ if err := world.saveInventory_locked(world.characters[1], inventory); err != nil {
+ t.Fatal(err)
+ }
+ }
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ conns[1].packets = nil
+
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 66})
+ playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ after, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t)
+
+ if scenario != "ordinary contents" {
+ if !bytes.Equal(before, after) || len(restored.characters[2].inventory.Items) != 1 {
+ t.Fatal("restricted root/child was transferred")
+ }
+ return
+ }
+ if !reflect.DeepEqual(restored.characters[2].inventory.Containers[4], []ownedItem{{ID: 5, Type: 51005, Template: 85366, Quality: 1, Slot: 20, Count: 25}}) ||
+ len(restored.characters[1].inventory.Containers) != 0 || len(restored.characters[2].inventory.Items) != 2 ||
+ binary.BigEndian.Uint32(conns[1].packets[0][16:20]) != 0x465a5d73 || binary.BigEndian.Uint32(conns[1].packets[1][33:37]) != 7 {
+ t.Fatal("filled bag did not preserve root, child identity, placement and quantity")
+ }
+ })
+ }
+}
+
+func TestPlayerTradeLoadedWeaponRetainsIdentityQualityAndAmmunition(t *testing.T) {
+ world, _ := newPlayerTradeWorld(t)
+ if granted, err := world.grantItem_locked(world.characters[1], 123742); err != nil || !granted {
+ t.Fatalf("gun: %v %v", granted, err)
+ }
+ inventory := world.characters[1].inventory
+ inventory.Items[2].Ammo = 3
+ if err := world.saveInventory_locked(world.characters[1], inventory); err != nil {
+ t.Fatal(err)
+ }
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 66})
+
+ playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ restored := newTestInventoryServer(t)
+
+ if !reflect.DeepEqual(restored.characters[2].inventory.Items[1], ownedItem{ID: 4, Type: 51018, Template: 123742, Quality: 1, Slot: 65, Count: 1, Ammo: 3}) ||
+ len(restored.characters[1].inventory.Items) != 2 || world.nextItem != 4 {
+ t.Fatal("trade recreated or reloaded the gun")
+ }
+}
+
+func TestPlayerTradeInterpolatedItemUsesBothNativeTemplateEndpoints(t *testing.T) {
+ world, conns := newPlayerTradeWorld(t)
+ if granted, err := world.grantItem_locked(world.characters[1], 85557); err != nil || !granted {
+ t.Fatalf("armor: %v %v", granted, err)
+ }
+ inventory := world.characters[1].inventory
+ inventory.Items[2].Quality = 101
+ if err := world.saveInventory_locked(world.characters[1], inventory); err != nil {
+ t.Fatal(err)
+ }
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ conns[1].packets = nil
+
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 66})
+ seed := conns[1].packets[0]
+ playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ restored := newTestInventoryServer(t)
+
+ if binary.BigEndian.Uint32(seed[29:33]) != 85557 || binary.BigEndian.Uint32(seed[33:37]) != 85556 || binary.BigEndian.Uint32(seed[37:41]) != 101 ||
+ restored.characters[2].inventory.Items[1].ID != 4 || restored.characters[2].inventory.Items[1].Template != 85557 || restored.characters[2].inventory.Items[1].Quality != 101 {
+ t.Fatal("peer display or durable transfer lost an interpolated template endpoint or QL")
+ }
+}
diff --git a/server/player_trading_test.go b/server/player_trading_test.go
@@ -0,0 +1,221 @@
+package main
+
+import (
+ "bytes"
+ "encoding/binary"
+ "reflect"
+ "slices"
+ "testing"
+)
+
+func newPlayerTradeWorld(t *testing.T) (*server, [2]*combatTestConn) {
+ t.Helper()
+ world, first := newEquipmentWorld(t)
+ peer := &character{id: 2, name: "Other Owner", level: 1, profession: 1, appearance: 277, playfield: 950, position: [3]float32{2, 0, 0}, health: 100, stats: testCharacterStats()}
+ peer.rotation[3] = 1
+ world.characters[2] = peer
+ second := &combatTestConn{}
+ world.clients[2] = &worldClient{id: 2, conn: second, target: true, ready: true}
+ if err := world.saveUser_locked(peer); err != nil {
+ t.Fatal(err)
+ }
+ if granted, err := world.grantItem_locked(world.characters[1], 85366); err != nil || !granted {
+ t.Fatalf("first stack: %v %v", granted, err)
+ }
+ if granted, err := world.grantItem_locked(peer, 25820); err != nil || !granted {
+ t.Fatalf("second stack: %v %v", granted, err)
+ }
+ for id, cash := range map[uint32]uint32{1: 20000, 2: 10000} {
+ inventory := world.characters[id].inventory
+ inventory.Credits = cash
+ if err := world.saveInventory_locked(world.characters[id], inventory); err != nil {
+ t.Fatal(err)
+ }
+ }
+ first.packets, second.packets = nil, nil
+ return world, [2]*combatTestConn{first, second}
+}
+
+func playerTradeRequest(t *testing.T, world *server, player, action uint32, first, second [2]uint32) {
+ t.Helper()
+ if err := world.handleTrade(world.clients[player], shopTradePacket([2]uint32{50000, player}, action, first, second)[20:]); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestPlayerTradeAdmissionAndNativeParticipants(t *testing.T) {
+ for _, scenario := range []string{"eligible", "self", "missing", "too far", "different playfield", "dead", "loading", "replaced", "equipment", "shop", "busy", "wrong type", "wrong tag"} {
+ t.Run(scenario, func(t *testing.T) {
+ world, conns := newPlayerTradeWorld(t)
+ first, second := [2]uint32{50000, 2}, [2]uint32{}
+ switch scenario {
+ case "self":
+ first[1] = 1
+ case "missing":
+ first[1] = 99
+ case "too far":
+ world.characters[2].position[0] = 5.01
+ case "different playfield":
+ world.characters[2].playfield = 705
+ case "dead":
+ world.characters[2].health = 0
+ case "loading":
+ world.clients[2].loading = true
+ case "replaced":
+ world.clients[2].ready = false
+ case "equipment":
+ world.clients[2].equipment = &equipmentMove{}
+ case "shop":
+ world.clients[2].shop = &shopTrade{}
+ case "busy":
+ world.clients[2].trade = &playerTrade{}
+ case "wrong type":
+ first[0] = 51017
+ case "wrong tag":
+ second[0] = 111
+ }
+
+ playerTradeRequest(t, world, 1, 0, first, second)
+
+ if scenario != "eligible" {
+ if world.clients[1].trade != nil || len(conns[0].packets) != 0 || len(conns[1].packets) != 0 {
+ t.Fatal("ineligible start opened or disturbed a trade")
+ }
+ return
+ }
+ if world.clients[1].trade == nil || world.clients[1].trade != world.clients[2].trade {
+ t.Fatal("participants did not share the same draft")
+ }
+ for _, conn := range conns {
+ if len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][24:28]) != 1 ||
+ binary.BigEndian.Uint32(conn.packets[0][33:37]) != 0 || binary.BigEndian.Uint32(conn.packets[0][41:45]) != 2 {
+ t.Fatal("start did not initialize the same native participant pair")
+ }
+ }
+ })
+ }
+}
+
+func TestPlayerTradePeerPartialStackDeliveryAndRemovalPreserveQuantity(t *testing.T) {
+ world, conns := newPlayerTradeWorld(t)
+ inventory := world.characters[1].inventory
+ inventory.Items[1].Count = 7
+ if err := world.saveInventory_locked(world.characters[1], inventory); err != nil {
+ t.Fatal(err)
+ }
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ conns[0].packets, conns[1].packets = nil, nil
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+ staged, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if !bytes.Equal(before, staged) || len(conns[1].packets) != 2 {
+ t.Fatal("staging changed durable ownership or omitted the counted peer row")
+ }
+ seed, move := conns[1].packets[0], conns[1].packets[1]
+ if binary.BigEndian.Uint32(seed[16:20]) != 0x052e2f0c || binary.BigEndian.Uint32(seed[24:28]) != 1 ||
+ binary.BigEndian.Uint32(seed[29:33]) != 85366 || binary.BigEndian.Uint32(seed[41:45]) != 7 ||
+ binary.BigEndian.Uint32(move[24:28]) != 1 || binary.BigEndian.Uint32(move[33:37]) != 4 || binary.BigEndian.Uint32(move[49:53]) != 48 {
+ t.Fatal("peer delivery did not seed/move an intact seven-charge remote row")
+ }
+ conns[1].packets = nil
+ playerTradeRequest(t, world, 1, 5, [2]uint32{50000, 1}, [2]uint32{108, 0})
+ if len(conns[1].packets) != 2 || binary.BigEndian.Uint32(conns[1].packets[0][24:28]) != 1 ||
+ binary.BigEndian.Uint32(conns[1].packets[0][33:37]) != 5 || binary.BigEndian.Uint32(conns[1].packets[1][29:33]) != 112 ||
+ binary.BigEndian.Uint32(conns[1].packets[1][37:41]) != 48 || len(world.clients[1].trade.items[0]) != 0 {
+ t.Fatal("peer removal did not clear its restored scratch row")
+ }
+}
+
+func TestPlayerTradeItemsCashAndReplayAreAtomic(t *testing.T) {
+ world, conns := newPlayerTradeWorld(t)
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+ playerTradeRequest(t, world, 2, 4, [2]uint32{50000, 2}, [2]uint32{104, 64})
+ playerTradeRequest(t, world, 1, 6, [2]uint32{0, 500}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 6, [2]uint32{0, 200}, [2]uint32{})
+ conns[0].packets, conns[1].packets = nil, nil
+
+ playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{})
+ if len(conns[0].packets) != 0 || len(conns[1].packets) != 1 || binary.BigEndian.Uint32(conns[1].packets[0][24:28]) != 2 ||
+ world.characters[1].inventory.Credits != 20000 {
+ t.Fatal("first consent lit the wrong lamp or transferred value early")
+ }
+ playerTradeRequest(t, world, 2, 6, [2]uint32{0, 200}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+ restored := newTestInventoryServer(t)
+
+ first, second := restored.characters[1].inventory, restored.characters[2].inventory
+ if first.Credits != 19700 || second.Credits != 10300 || world.nextItem != 3 ||
+ !reflect.DeepEqual(first, world.characters[1].inventory) || !reflect.DeepEqual(second, world.characters[2].inventory) ||
+ !reflect.DeepEqual(first.Items, []ownedItem{
+ {ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1},
+ {ID: 3, Type: 51005, Template: 25820, Quality: 1, Slot: 65, Count: 50},
+ }) || !reflect.DeepEqual(second.Items, []ownedItem{{ID: 2, Type: 51005, Template: 85366, Quality: 1, Slot: 64, Count: 25}}) ||
+ world.clients[1].trade != nil || world.clients[2].trade != nil {
+ t.Fatalf("wrong durable exchange: first=%+v second=%+v", first, second)
+ }
+ for _, conn := range conns {
+ var subjects []uint32
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x36284f6e && binary.BigEndian.Uint32(packet[33:37]) == 3 {
+ subjects = append(subjects, binary.BigEndian.Uint32(packet[24:28]))
+ }
+ }
+ if !slices.Equal(subjects, []uint32{1, 2}) {
+ t.Fatal("native completion directions missing or replayed")
+ }
+ }
+}
+
+func TestPlayerTradeDatabaseFailureDoesNotPublishEitherSide(t *testing.T) {
+ for _, trigger := range []string{
+ "CREATE TRIGGER fail_trade BEFORE UPDATE OF credits ON players WHEN NEW.id=2 BEGIN SELECT RAISE(ABORT, 'second balance'); END",
+ "CREATE TRIGGER fail_trade BEFORE INSERT ON item_locations WHEN NEW.item_id=3 BEGIN SELECT RAISE(ABORT, 'placement'); END",
+ } {
+ t.Run(trigger, func(t *testing.T) {
+ world, conns := newPlayerTradeWorld(t)
+ playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65})
+ playerTradeRequest(t, world, 2, 4, [2]uint32{50000, 2}, [2]uint32{104, 64})
+ playerTradeRequest(t, world, 1, 6, [2]uint32{0, 500}, [2]uint32{})
+ playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{})
+ before, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec(trigger); err != nil {
+ t.Fatal(err)
+ }
+ conns[0].packets, conns[1].packets = nil, nil
+
+ failed := world.handleTrade(world.clients[2], shopTradePacket([2]uint32{50000, 2}, 1, [2]uint32{}, [2]uint32{})[20:])
+ after, err := readTestItemStore(world)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if failed == nil || !bytes.Equal(before, after) || world.clients[1].trade == nil || world.clients[2].trade == nil ||
+ world.characters[1].inventory.Credits != 20000 || world.characters[2].inventory.Credits != 10000 ||
+ len(conns[0].packets) != 0 || len(conns[1].packets) != 0 {
+ t.Fatal("failed transaction published one side or sent a completion")
+ }
+ if _, err := world.db.Exec("DROP TRIGGER fail_trade"); err != nil {
+ t.Fatal(err)
+ }
+ playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
+ if newTestInventoryServer(t).characters[2].inventory.Credits != 10500 {
+ t.Fatal("retry did not commit both sides")
+ }
+ })
+ }
+}
diff --git a/server/ranged.go b/server/ranged.go
@@ -93,7 +93,7 @@ func (server *server) handleReload(client *worldClient, body []byte) error {
binary.BigEndian.Uint32(body[40:44]) == 104 && binary.BigEndian.Uint32(body[44:48]) == item.Slot
})
now := time.Now()
- accepted := weapon >= 0 && ammo >= 0 && client.equipment == nil && client.nanoCast == nil &&
+ accepted := client.trade == nil && weapon >= 0 && ammo >= 0 && client.equipment == nil && client.nanoCast == nil &&
!now.Before(client.reloadUntil) && !player.driving()
if accepted {
targetType, targetID := binary.BigEndian.Uint32(body[48:52]), binary.BigEndian.Uint32(body[52:56])
diff --git a/server/reclaim.go b/server/reclaim.go
@@ -93,7 +93,7 @@ func (server *server) takeReclaim(client *worldClient, body []byte) error {
server.mutex.Lock()
player := server.characters[client.id]
source := binary.BigEndian.Uint32(body[20:24])
- if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || client.equipment != nil ||
+ if !client.target || server.clients[client.id] != client || !client.ready || client.loading || player.health == 0 || client.equipment != nil || client.trade != nil ||
binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id ||
binary.BigEndian.Uint32(body[24:28]) != 50000 || binary.BigEndian.Uint32(body[28:32]) != client.id ||
binary.BigEndian.Uint32(body[32:36]) != 111 || source >= uint32(len(client.reclaimItems)) ||
diff --git a/server/shop_machines_test.go b/server/shop_machines_test.go
@@ -163,10 +163,10 @@ func TestShopRoomSaleCommitsItsOwnModifier(t *testing.T) {
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 {
+ if err := world.handleTrade(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 {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil {
t.Fatal(err)
}
restored := newTestInventoryServer(t).characters[1].inventory
@@ -194,7 +194,7 @@ func TestShopSpecialistSaleRevalidatesChangedRequirements(t *testing.T) {
if err := world.handleShopUse(client, request); err != nil || client.shop == nil {
t.Fatalf("specialist shop failed to open: %v", err)
}
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]); err != nil {
t.Fatal(err)
}
switch scenario {
@@ -206,7 +206,7 @@ func TestShopSpecialistSaleRevalidatesChangedRequirements(t *testing.T) {
player.stats.Spying.BreakingAndEntering = 177
}
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
restored := newTestInventoryServer(t).characters[1].inventory
if err != nil || client.shop != nil || player.inventory.Credits != 100 || len(player.inventory.Items) != 1 || restored.Credits != 100 || len(restored.Items) != 1 || restored.Items[0].ID != 1 {
diff --git a/server/shop_purchases_test.go b/server/shop_purchases_test.go
@@ -113,7 +113,7 @@ func TestShopPurchasePersistsOnceAfterRepeatedConcurrentAccept(t *testing.T) {
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 {
+ if err := world.handleTrade(client, body); err != nil {
t.Fatal(err)
}
}
@@ -125,7 +125,7 @@ func TestShopPurchasePersistsOnceAfterRepeatedConcurrentAccept(t *testing.T) {
var requests sync.WaitGroup
errors := make(chan error, 2)
for range 2 {
- requests.Go(func() { errors <- world.handleShopTrade(client, accept) })
+ requests.Go(func() { errors <- world.handleTrade(client, accept) })
}
requests.Wait()
close(errors)
@@ -134,7 +134,7 @@ func TestShopPurchasePersistsOnceAfterRepeatedConcurrentAccept(t *testing.T) {
t.Fatal(err)
}
}
- world.handleShopTrade(client, accept)
+ world.handleTrade(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) {
@@ -152,7 +152,7 @@ func TestShopPurchaseCancelAndRemoveLeaveCashAndOwnershipUnchanged(t *testing.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 {
+ if err := world.handleTrade(client, add); err != nil {
t.Fatal(err)
}
request := shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{51035, 3221488799}, [2]uint32{111, 0})[20:]
@@ -160,9 +160,9 @@ func TestShopPurchaseCancelAndRemoveLeaveCashAndOwnershipUnchanged(t *testing.T)
request = shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]
}
- err := world.handleShopTrade(client, request)
+ err := world.handleTrade(client, request)
if !cancel {
- err = world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err = world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
}
restored := newTestInventoryServer(t).characters[1].inventory
@@ -179,7 +179,7 @@ func TestShopPurchaseRejectsInsufficientCashAndFullInventoryAtomically(t *testin
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)
+ world.handleTrade(client, add)
switch scenario {
case "insufficient cash":
player.inventory.Credits = 227
@@ -189,7 +189,7 @@ func TestShopPurchaseRejectsInsufficientCashAndFullInventoryAtomically(t *testin
last := uint32(94)
if scenario == "two packages one slot" {
last = 93
- world.handleShopTrade(client, add)
+ world.handleTrade(client, add)
}
for slot := uint32(65); slot < last; slot++ {
item := player.inventory.Items[0]
@@ -205,7 +205,7 @@ func TestShopPurchaseRejectsInsufficientCashAndFullInventoryAtomically(t *testin
before.Items = slices.Clone(before.Items)
next := world.nextItem
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err := world.handleTrade(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) {
@@ -235,7 +235,7 @@ func TestShopPurchaseRejectsForgedCatalogReferences(t *testing.T) {
action = 5
}
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, action, first, second)[20:])
+ err := world.handleTrade(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")
@@ -247,20 +247,20 @@ func TestShopPurchaseRejectsForgedCatalogReferences(t *testing.T) {
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:])
+ world.handleTrade(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)
+ failed := world.handleTrade(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)
+ err := world.handleTrade(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 {
@@ -279,12 +279,12 @@ func TestShopMixedBasketUsesSaleProceedsAndFreedInventorySlot(t *testing.T) {
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 {
+ if err := world.handleTrade(client, request); err != nil {
t.Fatal(err)
}
}
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err := world.handleTrade(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}) {
@@ -295,12 +295,12 @@ func TestShopMixedBasketUsesSaleProceedsAndFreedInventorySlot(t *testing.T) {
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:])
+ world.handleTrade(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)
+ err := world.handleTrade(client, accept)
+ world.handleTrade(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 {
@@ -325,7 +325,7 @@ func TestShopPurchaseUniqueChecksCarriedItemsAndBasket(t *testing.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 {
+ if err := world.handleTrade(client, add); err != nil {
t.Fatal(err)
}
}
@@ -341,7 +341,7 @@ func TestShopPurchaseUniqueChecksCarriedItemsAndBasket(t *testing.T) {
request = shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]
}
- err := world.handleShopTrade(client, request)
+ err := world.handleTrade(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")
@@ -365,7 +365,7 @@ func TestShopRapidUnfundedAddsCannotCreateInvisiblePurchases(t *testing.T) {
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 {
+ if err := world.handleTrade(client, request); err != nil {
t.Fatal(err)
}
}
@@ -414,14 +414,14 @@ func TestShopChargedPackagesKeepCountsSlotsPricesAndDurableIdentities(t *testing
t.Fatal(err)
}
for _, index := range []uint32{1, 1, 0, 2} {
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221423263}, [2]uint32{111, index})[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221423263}, [2]uint32{111, index})[20:]); err != nil {
t.Fatal(err)
}
}
conn.packets = nil
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
- world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
restored := newTestInventoryServer(t).characters[1].inventory
expected := []ownedItem{
@@ -457,16 +457,16 @@ func TestShopChargedPurchaseRemoveAndCancelConsumeNoChargesOrCash(t *testing.T)
client, player := world.clients[1], world.characters[1]
before := slices.Clone(player.inventory.Items)
first, second := [2]uint32{51035, 3221423263}, [2]uint32{111, 1}
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, first, second)[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, first, second)[20:]); err != nil {
t.Fatal(err)
}
if action == 2 {
first, second = [2]uint32{}, [2]uint32{}
}
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, action, first, second)[20:])
+ err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, action, first, second)[20:])
if action == 5 {
- err = world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err = world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
}
restored := newTestInventoryServer(t).characters[1].inventory
@@ -484,11 +484,11 @@ func TestShopChargedPurchaseCapacityAndFinalFundsRejectWholeBasket(t *testing.T)
client, player := world.clients[1], world.characters[1]
player.inventory.Items[0] = ownedItem{ID: 1, Type: 51005, Template: 85366, Quality: 1, Slot: 64, Count: 7}
add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221423263}, [2]uint32{111, 1})[20:]
- world.handleShopTrade(client, add)
+ world.handleTrade(client, add)
last := uint32(94)
if scenario == "two packages one slot" {
last = 93
- world.handleShopTrade(client, add)
+ world.handleTrade(client, add)
}
if scenario == "cash changed" {
player.inventory.Credits, last = 18, 65
@@ -504,7 +504,7 @@ func TestShopChargedPurchaseCapacityAndFinalFundsRejectWholeBasket(t *testing.T)
before.Items = slices.Clone(before.Items)
next := world.nextItem
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err := world.handleTrade(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) {
@@ -526,12 +526,12 @@ func TestShopPartialPackageSaleAndPurchaseUseWholePackageQuote(t *testing.T) {
shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:],
shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221423263}, [2]uint32{111, 1})[20:],
} {
- if err := world.handleShopTrade(client, request); err != nil {
+ if err := world.handleTrade(client, request); err != nil {
t.Fatal(err)
}
}
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
restored := newTestInventoryServer(t).characters[1].inventory
if err != nil || restored.Credits != 3 || len(restored.Items) != 1 || restored.Items[0] != (ownedItem{ID: 2, Type: 51005, Template: 85366, Quality: 1, Slot: 64, Count: 25}) {
@@ -543,15 +543,15 @@ func TestShopChargedPurchaseRollbackThenRetryKeepsWholePackages(t *testing.T) {
world, conn := newMedicalPurchaseWorld(t)
client, player := world.clients[1], world.characters[1]
add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221423263}, [2]uint32{111, 1})[20:]
- world.handleShopTrade(client, add)
- world.handleShopTrade(client, add)
+ world.handleTrade(client, add)
+ world.handleTrade(client, add)
if _, err := world.db.Exec("CREATE TRIGGER reject_package BEFORE INSERT ON items WHEN NEW.id=3 BEGIN SELECT RAISE(FAIL, 'second package'); END"); err != nil {
t.Fatal(err)
}
conn.packets = nil
accept := shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]
- failed := world.handleShopTrade(client, accept)
+ failed := world.handleTrade(client, accept)
rejected := newTestInventoryServer(t).characters[1].inventory
if failed == nil || player.inventory.Credits != 1000 || len(player.inventory.Items) != 1 || world.nextItem != 1 || client.shop == nil || rejected.Credits != 1000 || len(rejected.Items) != 1 || len(conn.packets) != 0 {
t.Fatal("failed second package published a partial basket")
@@ -559,7 +559,7 @@ func TestShopChargedPurchaseRollbackThenRetryKeepsWholePackages(t *testing.T) {
if _, err := world.db.Exec("DROP TRIGGER reject_package"); err != nil {
t.Fatal(err)
}
- err := world.handleShopTrade(client, accept)
+ err := world.handleTrade(client, accept)
restored := newTestInventoryServer(t).characters[1].inventory
if err != nil || restored.Credits != 960 || len(restored.Items) != 3 || restored.Items[1].ID != 2 || restored.Items[2].ID != 3 || restored.Items[1].Count != 25 || restored.Items[2].Count != 25 || world.nextItem != 3 {
@@ -592,7 +592,7 @@ func TestShopPurchasedMedicalPackagesCanBeUsedAndPersistRemainingCharges(t *test
shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221423263}, [2]uint32{111, scenario.index})[20:],
shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:],
} {
- if err := world.handleShopTrade(client, request); err != nil {
+ if err := world.handleTrade(client, request); err != nil {
t.Fatal(err)
}
}
diff --git a/server/shop_stock_test.go b/server/shop_stock_test.go
@@ -68,16 +68,16 @@ func TestShopDevicesPurchasePersistsUniqueInterface(t *testing.T) {
t.Fatal(err)
}
add := shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3221816479}, [2]uint32{111, 0})[20:]
- if err := world.handleShopTrade(client, add); err != nil {
+ if err := world.handleTrade(client, add); err != nil {
t.Fatal(err)
}
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
restored := newTestInventoryServer(t).characters[1]
binary.BigEndian.PutUint32(request[20:24], 3)
world.handleShopUse(client, request)
- world.handleShopTrade(client, add)
- world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ world.handleTrade(client, add)
+ world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
if err != nil || restored.inventory.Credits != 108 || len(restored.inventory.Items) != 2 ||
restored.inventory.Items[1] != (ownedItem{ID: 2, Type: 51022, Template: 161699, Quality: 1, Slot: 65, Count: 1}) ||
@@ -101,12 +101,12 @@ func TestShopGeneralToolsPurchasesKeepDistinctRowsAndIdentities(t *testing.T) {
t.Fatal(err)
}
for _, index := range []uint32{1, 0} {
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3225158815}, [2]uint32{111, index})[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{51035, 3225158815}, [2]uint32{111, index})[20:]); err != nil {
t.Fatal(err)
}
}
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
restored := newTestInventoryServer(t).characters[1].inventory
if err != nil || restored.Credits != 9306 || !reflect.DeepEqual(restored.Items[1:], []ownedItem{
diff --git a/server/shops.go b/server/shops.go
@@ -21,7 +21,7 @@ type shopTrade struct {
func (server *server) canUseShop_locked(client *worldClient, machine gamedata.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 {
+ client.equipment != nil || client.trade != nil || player.playfield != machine.Playfield {
return false
}
position := predictedPosition_locked(player, client, time.Now())
@@ -150,12 +150,7 @@ func (server *server) abortShop_locked(client *worldClient) error {
return client.send(shopTradePacket([2]uint32{50000, client.id}, 2, [2]uint32{}, [2]uint32{}))
}
-func (server *server) restoreTradeItems_locked(client *worldClient, offers map[uint32]ownedItem, returned []uint32) error {
- if len(offers) == 0 {
- return nil
- }
- player := server.characters[client.id]
- inventory := player.inventory
+func restoredTradeInventory(inventory playerInventory, offers map[uint32]ownedItem, returned []uint32) (playerInventory, map[uint32]ownedItem) {
inventory.Items = slices.Clone(inventory.Items)
remaining := maps.Clone(offers)
for _, slot := range returned {
@@ -195,6 +190,15 @@ func (server *server) restoreTradeItems_locked(client *worldClient, offers map[u
}
}
slices.SortFunc(inventory.Items, func(a, b ownedItem) int { return cmp.Compare(a.ID, b.ID) })
+ return inventory, remaining
+}
+
+func (server *server) restoreTradeItems_locked(client *worldClient, offers map[uint32]ownedItem, returned []uint32) error {
+ if len(offers) == 0 {
+ return nil
+ }
+ player := server.characters[client.id]
+ inventory, remaining := restoredTradeInventory(player.inventory, offers, returned)
// Publish draft reservations only after their durable placement commits.
if !slices.Equal(inventory.Items, player.inventory.Items) {
if err := server.saveInventory_locked(player, inventory); err != nil {
@@ -252,7 +256,7 @@ func shopPendingSalePrice(item ownedItem, modifier uint32, computerLiteracy int3
return base + int64(float64(markup)*float64(base)*float64(float32(0.01)))
}
-func (server *server) handleShopTrade(client *worldClient, body []byte) error {
+func (server *server) handleTrade(client *worldClient, body []byte) error {
if len(body) != 40 {
return fmt.Errorf("invalid trade length")
}
@@ -260,11 +264,17 @@ func (server *server) handleShopTrade(client *worldClient, body []byte) error {
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 ||
+ if !client.target || server.clients[client.id] != client || !client.ready || client.loading ||
binary.BigEndian.Uint32(body[4:8]) != 50000 || binary.BigEndian.Uint32(body[8:12]) != client.id || binary.BigEndian.Uint32(body[16:20]) != 1 {
return nil
}
action := binary.BigEndian.Uint32(body[20:24])
+ if action == 0 || client.trade != nil {
+ return server.handlePlayerTrade_locked(client, body)
+ }
+ if client.shop == nil {
+ return nil
+ }
machine := gamedata.ShopMachines[client.shop.machine]
if action == 2 || !server.canUseShop_locked(client, machine) {
return server.abortShop_locked(client)
diff --git a/server/shops_test.go b/server/shops_test.go
@@ -45,10 +45,10 @@ func TestShopSalePricesUseNativeQualityChargesAndLiteracyRounding(t *testing.T)
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 {
+ if err := world.handleTrade(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 {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil {
t.Fatal(err)
}
@@ -190,7 +190,7 @@ func TestShopInvalidOffersLeaveCashAndInventoryUnchanged(t *testing.T) {
t.Fatal(err)
}
- err = world.handleShopTrade(client, body)
+ err = world.handleTrade(client, body)
after, readErr := readTestItemStore(world)
if err != nil || readErr != nil || !bytes.Equal(before, after) || client.shop != nil && len(client.shop.items) != 0 {
@@ -206,16 +206,16 @@ func TestShopNativeSalePersistsAndCannotBeReplayed(t *testing.T) {
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 {
+ if err := world.handleTrade(client, add); err != nil {
t.Fatal(err)
}
- world.handleShopTrade(client, add)
+ world.handleTrade(client, add)
staged := newTestInventoryServer(t).characters[1].inventory
- if err := world.handleShopTrade(client, accept); err != nil {
+ if err := world.handleTrade(client, accept); err != nil {
t.Fatal(err)
}
- world.handleShopTrade(client, accept)
- world.handleShopTrade(client, add)
+ world.handleTrade(client, accept)
+ world.handleTrade(client, add)
restored := newTestInventoryServer(t)
if staged.Credits != 100 || len(staged.Items) != 1 {
@@ -237,17 +237,17 @@ func TestShopCancelAndRemovePreserveTheOwnedItem(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:])
+ world.handleTrade(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 {
+ if err := world.handleTrade(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:])
+ world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
}
restored := newTestInventoryServer(t).characters[1].inventory
@@ -268,17 +268,17 @@ func TestShopRemovingAnOfferKeepsTheOtherTradeSlotsStable(t *testing.T) {
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 {
+ if err := world.handleTrade(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 {
+ if err := world.handleTrade(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 {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil {
t.Fatal(err)
}
restored := newTestInventoryServer(t).characters[1].inventory
@@ -294,12 +294,12 @@ func TestShopRemovingAnOfferKeepsTheOtherTradeSlotsStable(t *testing.T) {
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:])
+ world.handleTrade(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)
+ err := world.handleTrade(client, accept)
+ world.handleTrade(client, accept)
restored := newTestInventoryServer(t).characters[1].inventory
if err == nil || restored.Credits != 705 || len(restored.Items) != 0 || client.shop != nil {
@@ -310,7 +310,7 @@ func TestShopLostCompletionReplyDoesNotReplayTheSale(t *testing.T) {
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 {
+ if err := world.handleTrade(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:]
@@ -318,7 +318,7 @@ func TestShopConcurrentAcceptAwardsCreditsOnce(t *testing.T) {
var requests sync.WaitGroup
for range 2 {
- requests.Go(func() { errors <- world.handleShopTrade(client, accept) })
+ requests.Go(func() { errors <- world.handleTrade(client, accept) })
}
requests.Wait()
close(errors)
@@ -350,10 +350,10 @@ func TestShopClanTerminalUsesItsAuthoredSaleModifier(t *testing.T) {
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 {
+ if err := world.handleTrade(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 {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil {
t.Fatal(err)
}
restored := newTestInventoryServer(t).characters[1].inventory
@@ -366,7 +366,7 @@ func TestShopClanTerminalUsesItsAuthoredSaleModifier(t *testing.T) {
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 {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]); err != nil {
t.Fatal(err)
}
conn.packets = nil
@@ -378,7 +378,7 @@ func TestShopEquippingAnOfferedItemCancelsTheSale(t *testing.T) {
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 {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil {
t.Fatal(err)
}
restored := newTestInventoryServer(t).characters[1].inventory
@@ -401,7 +401,7 @@ func TestShopCommitFailureRollsBackCashAndOwnership(t *testing.T) {
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:])
+ world.handleTrade(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)
@@ -411,7 +411,7 @@ func TestShopCommitFailureRollsBackCashAndOwnership(t *testing.T) {
}
conn.packets = nil
- err = world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err = world.handleTrade(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 ||
@@ -478,7 +478,7 @@ func TestShopRejectsChangedOffersAndCreditOverflow(t *testing.T) {
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:])
+ world.handleTrade(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
@@ -499,7 +499,7 @@ func TestShopRejectsChangedOffersAndCreditOverflow(t *testing.T) {
before.Items[0].Slot = 64
}
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err := world.handleTrade(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/signed_stats_test.go b/server/signed_stats_test.go
@@ -162,11 +162,11 @@ func TestSignedLiteracyReachesDurableVendorSale(t *testing.T) {
player.stats.TradeRepair.ComputerLiteracy = 0
player.activeNanos = syntheticNanoModifiers(t, [][2]int32{{161, -40}})
- err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:])
+ err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:])
if err != nil {
t.Fatal(err)
}
- err = world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
+ err = world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:])
restored := newTestInventoryServer(t).characters[1]
if err != nil || player.inventory.Credits != 699 || restored.inventory.Credits != 699 || len(player.inventory.Items) != 0 || len(restored.inventory.Items) != 0 {
diff --git a/server/state.go b/server/state.go
@@ -87,6 +87,7 @@ type worldClient struct {
reclaimItems []uint32
backpacks map[uint32]backpackHandle
shop *shopTrade
+ trade *playerTrade
bank *bankSession
useSequence uint32
selectedTarget [2]uint32
diff --git a/server/trade_restoration_test.go b/server/trade_restoration_test.go
@@ -39,13 +39,13 @@ func TestShopRestoresOffersIntoNativeFirstFreeSlots(t *testing.T) {
t.Fatal(err)
}
for _, slot := range scenario.offer {
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, slot})[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, slot})[20:]); err != nil {
t.Fatal(err)
}
}
if scenario.remove {
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{50000, 1}, [2]uint32{108, 1})[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{50000, 1}, [2]uint32{108, 1})[20:]); err != nil {
t.Fatal(err)
}
if client.shop.items[0].Slot != 65 || player.inventory.Items[1].Slot != 64 {
@@ -53,7 +53,7 @@ func TestShopRestoresOffersIntoNativeFirstFreeSlots(t *testing.T) {
}
}
conn.packets = nil
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]); err != nil {
t.Fatal(err)
}
restored := newTestInventoryServer(t).characters[1].inventory
@@ -77,21 +77,21 @@ func TestShopFullInventoryCanRemoveReofferAndSellChargedItems(t *testing.T) {
}
}
for _, slot := range []uint32{64, 93} {
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, slot})[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, slot})[20:]); err != nil {
t.Fatal(err)
}
}
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{50000, 1}, [2]uint32{108, 1})[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 5, [2]uint32{50000, 1}, [2]uint32{108, 1})[20:]); err != nil {
t.Fatal(err)
}
if client.shop.items[0].Slot != 93 || player.inventory.Items[29].Slot != 64 {
t.Fatal("full inventory did not reserve the remaining offer away from the restored kit")
}
- if err := world.handleShopTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 64})[20:]); err != nil {
+ if err := world.handleTrade(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 {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 1, [2]uint32{}, [2]uint32{})[20:]); err != nil {
t.Fatal(err)
}
restored := newTestInventoryServer(t).characters[1].inventory
@@ -111,7 +111,7 @@ func TestShopRestorationFailureRetainsDraftAndCanRetry(t *testing.T) {
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, 70})[20:]); err != nil {
+ if err := world.handleTrade(client, shopTradePacket([2]uint32{50000, 1}, 4, [2]uint32{50000, 1}, [2]uint32{104, 70})[20:]); err != nil {
t.Fatal(err)
}
before, err := readTestItemStore(world)
@@ -124,7 +124,7 @@ func TestShopRestorationFailureRetainsDraftAndCanRetry(t *testing.T) {
conn.packets = nil
request := shopTradePacket([2]uint32{50000, 1}, 2, [2]uint32{}, [2]uint32{})[20:]
- failed := world.handleShopTrade(client, request)
+ failed := world.handleTrade(client, request)
after, err := readTestItemStore(world)
if err != nil {
t.Fatal(err)
@@ -136,7 +136,7 @@ func TestShopRestorationFailureRetainsDraftAndCanRetry(t *testing.T) {
if _, err := world.db.Exec("DROP TRIGGER fail_restore"); err != nil {
t.Fatal(err)
}
- if err := world.handleShopTrade(client, request); err != nil {
+ if err := world.handleTrade(client, request); err != nil {
t.Fatal(err)
}
if client.shop != nil || newTestInventoryServer(t).characters[1].inventory.Items[0].Slot != 64 {
diff --git a/server/world_actions.go b/server/world_actions.go
@@ -147,6 +147,9 @@ func (server *server) handleMovement(client *worldClient, body []byte) error {
case 22, 23:
character.running = binary.BigEndian.Uint32(body[16:20]) == 23
}
+ if client.trade != nil && !server.playerTradeAvailable_locked(client.trade.clients[0], client.trade.clients[1]) {
+ server.cancelPlayerTrade_locked(client)
+ }
// Locomotion interrupts an admitted cast; rotation-only updates do not.
updates := make(map[*worldClient][][]byte)
if client.bank != nil && !server.bankAvailable_locked(client) {