aorecomp

Anarchy Online classic in the browser

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


commit 8629e7b1d17c7c6aec1cfa5ef98396afd2749849
parent 69598c002ee87557a6edd7a341f3a26852dc0d63
Author: anon <anon@example.com>
Date:   Wed,  4 Nov 2026 02:48:22 +0000

Deliver mission key trade offers as live item references

Diffstat:
MTODO.md | 6++++--
Mdocs/mission-keys.md | 32+++++++++++++++++++++++++++++++-
Mserver/browser_mission_key_name_test.go | 14++------------
Aserver/browser_named_key_trade_test.go | 105+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aserver/mission_key_packet.go | 19+++++++++++++++++++
Aserver/mission_key_trade_packet_test.go | 43+++++++++++++++++++++++++++++++++++++++++++
Mserver/player_trading.go | 6++++++
Atools/client/test_named_key_trade.mjs | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 298 insertions(+), 15 deletions(-)

diff --git a/TODO.md b/TODO.md @@ -2475,8 +2475,10 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md). now displays two distinct controlled live-key names in native tooltips/info; its missing carried-slot translation is fixed. A controlled named key now retains its live name through bank reopening and withdrawal, with ordinary - uninstantiated keys still usable. Production destination labels and their - trade/reclaim/reconnect behavior remain unimplemented. + uninstantiated keys still usable. Live FullUpdate/Add7 trade delivery now + passes controlled naming, cancellation/repeated offers, acceptance and native + recipient copying with exact cold bindings. Production destination labels + and their reclaim/reconnect behavior remain unimplemented. See [mission keys](docs/mission-keys.md). Cover held, banked, traded, deleted and reclaimed keys; possession of an unrelated template28577 must never admit a player to another mission. diff --git a/docs/mission-keys.md b/docs/mission-keys.md @@ -109,7 +109,7 @@ test labels are not recovered historical destination wording or mission bindings Captures and protocol verification are in `local/mission-key-name/`. Production keys and copies still display the base name. Destination publication, -historical label wording and live-item trade/reclaim/reconnect behavior remain +historical label wording and live-item reclaim/reconnect behavior remain open. The original activation ignores already-existing dynels, so fresh creation alone cannot prove those lifetime paths. Historical key retention after completion/abandonment remains separately unresolved. @@ -140,3 +140,33 @@ The before/after captures are `local/mission-key-name/20261103-182253/` and `20261103-182555/`; the corrected check takes17 seconds. The bank fixture position and labels are controlled. This does not establish historical destination wording or name publication on cold reconnect. + +### Player trade delivery + +The peer's ordinary AddTemplate seed rebuilt a live named key as a template +proxy, displaying only the original base name. Mission-key offers now follow +the existing count-one live-item route: a generic FullUpdate seeds the exact +type51053 instance, then Trade7 references that identity. The shared +`missionKeyPacket` encoder also supplies the controlled bank/name fixture. +Other ordinary counted offers keep their existing template path. + +`TestBrowserNamedMissionKeyTrade` gives the host template a controlled label and +seeds the owner's live instance with that same label. The original client +resource stays unchanged. This isolates transport from the still-unimplemented +per-assignment name producer. The native peer displays `Destination A` with its +own temporary prefix during the offer, then without that prefix after acceptance. +Cancellation, a repeated offer and acceptance retain the usable exact instance. +The recipient then uses a controlled reusable duplicator on that live key through +real Shift-right-click input. Cold loading retains original2 and copy4 bound to +assignment2, tool3, the giver's axe1 and both unchanged wallets. No second journal +or new assignment is granted. + +The public-handler wire regression checks FullUpdate before Trade7, the exact +identity/slot and terminated base name, and no ownership/checkpoint writes for +an offer. Production currently supplies the original base template name to this +transport; deriving destination labels from persisted bindings remains open. +The copied result also retains its current base-name delivery path. + +The before capture is `local/named-key-trade/20261103-183641/`; the corrected +17-second trade/copy check is `20261103-184311/`. These are controlled protocol +and ownership fixtures, not earned progression or recovered historical wording. diff --git a/server/browser_mission_key_name_test.go b/server/browser_mission_key_name_test.go @@ -4,7 +4,6 @@ import ( "cmp" "context" "crypto/sha256" - "encoding/binary" "encoding/json" "fmt" "net/http" @@ -53,17 +52,8 @@ func TestBrowserMissionKeyNameRoute(t *testing.T) { defer world.mutex.Unlock() // Original SimpleItem11 with distinct controlled labels, not mission bindings. for index, name := range []string{"Mission Key to Destination A", "Mission Key to Destination B"} { - var body []byte - for _, value := range []uint32{11, 50000, 1, player.playfield, 0, 0} { - body = binary.BigEndian.AppendUint32(body, value) - } - body = append(body, 104, byte(64+index)) - for _, value := range []uint32{5 * 1009, 23, 28577, 701, 1, 702, 28577, 703, 28577, uint32(len(name) + 1)} { - body = binary.BigEndian.AppendUint32(body, value) - } - body = append(body, []byte(name)...) - body = append(body, 0) - if err := world.clients[1].send(n3Packet(0x3b11256f, 51053, uint32(index+1), body)); err != nil { + item := ownedItem{ID: uint32(index + 1), Type: 51053, Template: 28577, Quality: 1, Slot: uint32(64 + index), Count: 1} + if err := world.clients[1].send(missionKeyPacket(1, player.playfield, item, 104, name)); err != nil { t.Error(err) http.Error(w, err.Error(), http.StatusInternalServerError) return diff --git a/server/browser_named_key_trade_test.go b/server/browser_named_key_trade_test.go @@ -0,0 +1,105 @@ +package main + +import ( + "ao/server/gamedata" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "slices" + "testing" + "time" +) + +func TestBrowserNamedMissionKeyTrade(t *testing.T) { + if os.Getenv("AO_GAME_TEST") != "1" { + t.Skip("set AO_GAME_TEST=1 for named mission-key trading") + } + _, source, _, _ := runtime.Caller(0) + root := filepath.Dir(filepath.Dir(source)) + output := filepath.Join(root, "local/named-key-trade", time.Now().Format("20060102-150405")) + original := gamedata.ItemTemplates[28577] + definition := *original + definition.Name = "Mission Key to Destination A" + gamedata.ItemTemplates[28577] = &definition + t.Cleanup(func() { gamedata.ItemTemplates[28577] = original }) + world, _ := newAcceptedMissionWorld(t) + world.characters[2] = &character{id: 2, level: 1, profession: 1, health: 100, stats: testCharacterStats()} + for index := range 2 { + player := world.characters[uint32(index+1)] + player.name, player.appearance = fmt.Sprint("Trader", index), 0x515 + player.playfield, player.position = 950, [3]float32{60, 14.75, 53 - float32(index)*3} + player.rotation = [4]float32{0, 1, 0, 0} + player.browserTokenHash = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprint("named-key-trade-", index)))) + if err := world.saveUser_locked(player); err != nil { + t.Fatal(err) + } + if err := world.savePosition_locked(player); err != nil { + t.Fatal(err) + } + } + if granted, err := world.grantItem_locked(world.characters[2], 28564); err != nil || !granted { + t.Fatal(granted, err) + } + before := world.characters[1].inventory + if err := world.db.Close(); err != nil { + t.Fatal(err) + } + world = newServerForTest(t) + mux := http.NewServeMux() + mux.Handle("/", world.httpHandler()) + mux.HandleFunc("GET /test-state", func(w http.ResponseWriter, r *http.Request) { + world.mutex.Lock() + defer world.mutex.Unlock() + json.NewEncoder(w).Encode(map[string]any{"owner": world.characters[1].inventory, "peer": world.characters[2].inventory}) + }) + // Seed the owner with a controlled instance label; the native peer uses normal trade delivery. + mux.HandleFunc("POST /test-name", func(w http.ResponseWriter, r *http.Request) { + world.updateMutex.Lock() + defer world.updateMutex.Unlock() + world.mutex.Lock() + defer world.mutex.Unlock() + player := world.characters[1] + if err := world.clients[1].send(missionKeyPacket(1, player.playfield, player.inventory.Items[1], 104, definition.Name)); err != nil { + t.Error(err) + http.Error(w, err.Error(), http.StatusInternalServerError) + } + }) + host := httptest.NewServer(mux) + t.Cleanup(host.Close) + closeTestBrowserStreams(t, world) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute) + defer cancel() + + command := exec.CommandContext(ctx, "node", filepath.Join(root, "tools/client/test_named_key_trade.mjs"), host.URL, output) + command.Dir, command.Stdout, command.Stderr = root, os.Stdout, os.Stderr + err := command.Run() + t.Logf("Browser artifacts: %s", output) + + if err != nil { + t.Fatal(err) + } + cold := newTestInventoryServer(t) + expected := []ownedItem{{ID: 2, Type: 51053, Template: 28577, Quality: 1, Slot: 65, Count: 1}, + {ID: 3, Type: 51054, Template: 28564, Quality: 1, Slot: 64, Count: 1}, + {ID: 4, Type: 51053, Template: 28577, Quality: 1, Slot: 66, Count: 1}} + if !slices.Equal(world.characters[1].inventory.Items, before.Items[:1]) || + !slices.Equal(cold.characters[1].inventory.Items, before.Items[:1]) || + !slices.Equal(world.characters[2].inventory.Items, expected) || !slices.Equal(cold.characters[2].inventory.Items, expected) || + cold.characters[1].inventory.Credits != before.Credits || cold.characters[2].inventory.Credits != 0 || + world.nextItem != 4 || cold.nextItem != 4 { + t.Fatal("named key trade changed identities, charges, cash or allocation") + } + for _, id := range []uint32{2, 4} { + var mission uint32 + if err := cold.db.QueryRow("SELECT mission_id FROM mission_keys WHERE item_id=?", id).Scan(&mission); err != nil || mission != 2 { + t.Fatal("trade/copy lost the exact mission binding", id, mission, err) + } + } +} diff --git a/server/mission_key_packet.go b/server/mission_key_packet.go @@ -0,0 +1,19 @@ +package main + +import "encoding/binary" + +func missionKeyPacket(owner, playfield uint32, item ownedItem, page uint32, name string) []byte { + // SimpleItem11 carries its owned placement, template stats and C name. + var body []byte + for _, value := range []uint32{11, 50000, owner, playfield, 0, 0} { + body = binary.BigEndian.AppendUint32(body, value) + } + body = append(body, byte(page), byte(item.Slot)) + low, high := item.templateIDs() + for _, value := range []uint32{5 * 1009, 23, item.Template, 701, item.Quality, 702, low, 703, high, uint32(len(name) + 1)} { + body = binary.BigEndian.AppendUint32(body, value) + } + body = append(body, []byte(name)...) + body = append(body, 0) + return n3Packet(0x3b11256f, item.Type, item.ID, body) +} diff --git a/server/mission_key_trade_packet_test.go b/server/mission_key_trade_packet_test.go @@ -0,0 +1,43 @@ +package main + +import ( + "bytes" + "encoding/binary" + "testing" +) + +func TestPlayerTradeMissionKeyUsesLiveReference(t *testing.T) { + world, output := newPlayerTradeWorld(t) + player := world.characters[1] + player.inventory.Items[1] = ownedItem{ID: 2, Type: 51053, Template: 28577, Quality: 1, Slot: 65, Count: 1} + if err := world.saveInventory_locked(player, player.inventory); err != nil { + t.Fatal(err) + } + playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{}) + before, err := readTestItemStore(world) + if err != nil { + t.Fatal(err) + } + auditCheckpointWrites(t, world) + output[0].packets, output[1].packets = nil, nil + + playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 65}) + after, err := readTestItemStore(world) + + if err != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 || + len(output[0].packets) != 1 || len(output[1].packets) != 2 { + t.Fatal("key offer changed durable ownership or omitted native delivery", err) + } + packet := output[1].packets[0] + if binary.BigEndian.Uint32(packet[16:20]) != 0x3b11256f || + binary.BigEndian.Uint32(packet[20:24]) != 51053 || binary.BigEndian.Uint32(packet[24:28]) != 2 || + packet[53] != 104 || packet[54] != 49 || binary.BigEndian.Uint32(packet[91:95]) != 15 || + string(packet[95:110]) != "Mission Key to\x00" { + t.Fatalf("key seed lost identity, placement or terminated name: %x", packet) + } + packet = output[1].packets[1] + // The connection supplies its sequence before the opcode and message contents. + if !bytes.Equal(packet[16:], targetPacket(shopTradePacket([2]uint32{50000, 2}, 7, [2]uint32{50000, 1}, [2]uint32{51053, 2}))[16:]) { + t.Fatalf("peer did not reference the exact live key after its FullUpdate: %x", packet) + } +} diff --git a/server/player_trading.go b/server/player_trading.go @@ -237,6 +237,12 @@ func (server *server) handlePlayerTrade_locked(client *worldClient, body []byte) } return peer.send(shopTradePacket([2]uint32{50000, peer.id}, 7, owner, [2]uint32{item.Type, item.ID})) } + if item.Type == 51053 && item.Template == 28577 { + if err := peer.send(missionKeyPacket(client.id, player.playfield, item, 104, item.templateDefinition().Name)); 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() diff --git a/tools/client/test_named_key_trade.mjs b/tools/client/test_named_key_trade.mjs @@ -0,0 +1,88 @@ +import assert from 'node:assert/strict'; +import {createRequire} from 'node:module'; +import {GameTest} from './game_test.mjs'; + +const {chromium} = createRequire(import.meta.url)('playwright'); +const [url, output] = process.argv.slice(2); +const browser = await chromium.launch({executablePath: '/usr/bin/chromium', args: [ + '--enable-gpu', '--use-gl=angle', '--use-angle=gl', '--no-sandbox', '--disable-dev-shm-usage', + '--disable-background-timer-throttling', '--disable-renderer-backgrounding']}); +const games = []; +const cell = (game, page, slot) => game.state.grids.flatMap(grid => grid.cells).find(cell => + cell.identity[0] === page && cell.identity[1] === slot && !cell.dummy); +const click = async (game, page, slot) => { + const source = cell(game, page, slot); + assert(source, `native source ${page}/${slot} must remain usable`); + await game.click((source.bounds[0] + source.bounds[2]) / 2, (source.bounds[1] + source.bounds[3]) / 2); +}; +async function inspect(game, page, slot, directory) { + await game.page.keyboard.down('Shift'); + try { await click(game, page, slot); } + finally { await game.page.keyboard.up('Shift'); } + await game.save(directory); + await game.key('Escape'); +} +try { + for (const index of [0, 1]) { + const context = await browser.newContext({viewport: {width: 1024, height: 768}}); + await context.addCookies([{name: 'ao_client', value: 'named-key-trade-' + index, url}]); + const page = await context.newPage(), game = await GameTest.attach(page); + games.push(game); + await page.goto(url); + await game.ready(); + await page.waitForFunction(() => touchRegion(500, 400)?.world === true); + await game.snapshot(); + } + const [owner, peer] = games; + const server = async () => (await owner.page.request.get(url + '/test-state')).json(); + await owner.key('KeyI'); + assert((await owner.page.request.post(url + '/test-name')).ok()); + await owner.wait('owner has the original live key', () => owner.events.some(event => + event.direction === 'framereceived' && event.opcode === '3b11256f' && event.actor[1] === 2)); + await inspect(owner, 104, 49, output + '/owner-info'); + if (!owner.state.camera.firstPerson) await owner.key('F8'); + for (const attempt of [0, 1]) { + await owner.click(...await owner.pick(50000, 2), 'right'); + await Promise.all(games.map(game => game.wait('player trade opens', state => state.regions.some(region => + region[0] === 832 && region[1] === 0 && region[2] === 1024 && region[3] === 247)))); + const sequence = peer.sequence; + await click(owner, 104, 49); + await owner.wait('key picked', state => state.dragged[0] === 104 && state.dragged[1] === 49); + await owner.click(864, 172); + await peer.wait('peer sees the key offer', () => cell(peer, 208, 0)); + await inspect(peer, 208, 0, output + '/peer-info-' + attempt); + await peer.wait('peer receives the exact live key', () => peer.events.some(event => event.sequence > sequence && + event.direction === 'framereceived' && event.opcode === '3b11256f' && event.actor[0] === 51053 && event.actor[1] === 2)); + if (attempt === 0) { + await owner.click(945, 228); + await owner.wait('cancelled source remains usable', () => cell(owner, 104, 49)); + await inspect(owner, 104, 49, output + '/cancelled-info'); + } + } + await owner.click(874, 228); + await peer.click(874, 228); + await peer.wait('recipient owns the same live key', state => peer.local(state).inventory.some(item => item.id === 2 && item.slot === 49)); + await peer.key('KeyI'); + await peer.wait('received source is usable', () => cell(peer, 104, 49)); + await inspect(peer, 104, 49, output + '/received-info'); + + // A received live key must also work as the existing duplicator's target. + await click(peer, 104, 48); + await peer.wait('duplicator picked', state => state.dragged[0] === 104 && state.dragged[1] === 48); + const key = cell(peer, 104, 49); + await peer.page.keyboard.down('Shift'); + try { await peer.click((key.bounds[0] + key.bounds[2]) / 2, (key.bounds[1] + key.bounds[3]) / 2, 'right'); } + finally { await peer.page.keyboard.up('Shift'); } + await peer.wait('live received key is copied', state => peer.local(state).inventory.filter(item => item.templates[0] === 28577).length === 2 && cell(peer, 104, 50)); + await peer.key('Escape'); + await peer.wait('original and reusable tool remain usable', () => cell(peer, 104, 48) && cell(peer, 104, 49)); + await peer.save(output + '/copied'); + const result = await server(); + assert.deepEqual(result.owner.Items.map(item => item.ID), [1]); + assert.deepEqual(result.peer.Items.map(item => [item.ID, item.Slot]), [[2, 65], [3, 64], [4, 66]]); + for (const game of games) assert.deepEqual(game.errors, []); + console.log('PASS: live named key trade, repeated offers, native recipient copying and cold bindings'); +} finally { + try { for (const [index, game] of games.entries()) await game.save(output + '/final-' + index); } + finally { await browser.close(); } +}