commit 076fbd1b5ca973c05b38f2eee812398a62d99c42
parent 60397dff3d8e1177737f8511c87b71fd9e52dfa6
Author: anon <anon@example.com>
Date: Thu, 22 Oct 2026 19:21:38 +0000
Persist corpse credits and match native collection
Diffstat:
8 files changed, 380 insertions(+), 6 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -189,7 +189,7 @@ are recorded in [reclaim](docs/reclaim.md).
same item produce one owner and no duplicate or lost item.
- [ ] Enforce individual loot rights. Check: the entitled player can loot and
an unrelated player cannot; expiry follows an explicit policy.
-- [ ] Award and retain credits. Check: taking a known corpse credit amount
+- [x] Award and retain credits. Check: taking a known corpse credit amount
changes the balance once and survives reconnect and restart.
- [ ] Roll loot for one creature profile. Check: controlled rolls select the
documented entries and quantities, including an empty result where allowed.
@@ -199,6 +199,8 @@ are recorded in [reclaim](docs/reclaim.md).
The fixed-item checks use a controlled fixture after a real combat kill;
production drop tables remain a separate task. Native packet evidence and
current policy limits are recorded in [corpse and loot protocol](docs/corpse-loot.md).
+Known-amount credit collection and native balance limits are verified in
+[corpse credits](docs/corpse-credits.md); creature cash-drop formulas remain open.
## Character progression
diff --git a/docs/corpse-credits.md b/docs/corpse-credits.md
@@ -0,0 +1,113 @@
+# Corpse credits
+
+Cash is native stat 61. The server persists a player's balance in the same
+`inventory.yaml` replacement as owned items and supplies it in FullCharacter
+on login. Older inventories default to zero. Creature cash amounts remain
+unconfigured; controlled fixtures supply known amounts for this milestone.
+
+## Native collection
+
+The selected 14.9.1 `kkr.dll` SHA256 is
+`a37bc1c15053fdcc5572772309f7074c4f83baffe2faa164df40b059b7c480c0`.
+Addresses below use its original 0x10000000 base; maintained generated C uses
+0x36000000. The corpse constructor `1008bf80` initializes Cash 61 to zero and
+marks it for replication. CorpseFullUpdate carries a supplied amount in its
+SimpleItem stat list.
+
+There is no separate collection request in this path. Successful corpse Use 3
+calls `1008c510`, after base Chest Use toggles the loot window. It reads the
+corpse's cash, adds it to the local character, prints the native receipt and
+zeros the corpse's cash. Opening, closing and reopening therefore cannot
+collect the same local amount twice. Zero cash produces no receipt. The
+shipped `cd_image/text/help/combat.txt` associates the credit bonus with looting
+the corpse, consistent with this path.
+
+The request is GenericCmd `0x52526858`, outer identity 50000/playerID, body
+`{0, sequence, 3, 1, 50000, playerID, 51050, corpseID}`. Success echoes state 1;
+failure state 2 does not invoke Use. Success reaches `10087a70 -> 1004ccc0 ->
+1004d780`, schedules category 4 completion, and later executes through
+`1004d880 -> 1004c9f0` to the corpse's Use virtual method. An absolute owner
+Cash update immediately after ACK can precede this deferred addition and
+cause a second displayed gain. Packet order alone does not establish callback
+completion.
+
+The server saves the resulting balance before success and clears the
+authoritative corpse amount only after the save succeeds. It relies on the
+accepted native Use to update the owner's balance and receipt. The Cash
+setter emits the native stat-change event that refreshes the HUD. No separate
+server receipt or immediate owner balance correction is sent. Reconnect and
+restart initialize the durable authoritative balance again.
+
+Other ready observers who know the corpse receive StatIIR `0x2b333d6e`, outer
+identity 51050/corpseID, body `{61,0}`. Its noncharacter branch `100b2e60`
+resolves the visual dynel, adjusts to the underlying item and calls its stat
+setter. The owner is excluded: clearing its amount before deferred Use would
+suppress the native addition. Later interest snapshots publish zero cash.
+
+## Amount and balance boundaries
+
+`1008c510` treats signed corpse amounts outside 0..100000 as 100. This includes
+negative bit patterns and positive values above 100000. The server mirrors
+that conversion. No source establishes a historical creature cash-drop
+formula or proves that such invalid amounts occurred in ordinary play.
+
+Character setter `1006e030` maps stat 61 through the compressed switch table
+to `1006e198`. It accepts 0..1,000,000,000 inclusive and rejects negative or
+larger assignments. The exact table entries and original comparison bytes
+are retained in `local/corpse-credit-smoke/cash-stat-switch.json`.
+
+The server mirrors the recovered whole-addition behavior: if adding the
+corpse amount would exceed 1,000,000,000, the balance stays unchanged and the
+corpse amount is consumed. Native Use still prints its receipt in this case,
+even though the setter rejected the increase. This is a verified client
+quirk; the original server's overflow, partial-collection and team-sharing
+policies remain unknown. Inventories above the native accepted balance
+range are rejected during loading.
+
+## Ownership and remaining scope
+
+Use shares the existing corpse visibility, playfield, range, life, expiry and
+session checks. The current killer-only server policy remains provisional:
+the shipped `OnSelectRemains.txt` describes majority-damage player/team loot
+rights, whose separate TODO remains open. Team money splitting and public
+loot expiry are not inferred from this cash path.
+
+Credits and item ownership share one inventory file, so collecting an item
+after cash does not erase the balance. Failed saves preserve both the
+previous balance and corpse cash. Repeated sequences, later close/reopen
+and competing unauthorized users cannot repeat the award. Corpses remain
+runtime state; taken credits survive restart, while untaken corpse contents
+have the existing nonpersistent lifecycle.
+
+Native source streams, switch tables, shipped help, fixtures, packet logs and
+read-only probes are retained under `local/corpse-credit-smoke/`. See
+[corpse and loot protocol](corpse-loot.md) for the surrounding container flow.
+
+## Verification
+
+Go tests exercise durable collection, replay, item pickup, amount boundaries,
+invalid and competing requests, failed saves, closed owner output and invalid
+persistent balances. The full maintained server suite and three race-detector
+repetitions of all credit tests and the concurrent pickup and expiry tests
+pass. An initial broad race run exceeded Go's time limit while repeatedly
+parsing zone-link YAML during fixture setup. Credit tests now use a focused
+corpse fixture; existing loot tests and WASM checks cover the combat kill.
+
+Two real WASM clients exercised a known 123-credit corpse after an actual
+combat kill. The entitled player's native Cash and HUD changed 250 -> 373;
+the other player's balance stayed 77 and its corpse Cash changed 123 -> 0.
+Close/reopen did not grant again. A later contested Use had both clients send
+actual requests in the same second, with the unauthorized request first;
+only the entitled player received the award. Item pickup preserved the cash.
+Reconnect and server restart restored 373 and 77 in both server state and the
+respective clients' native stats, alongside the taken item.
+
+Native Use also verified 0 + 100000, 250 + 100001, 250 + 0xffffffff,
+999999999 + 1 and 999999999 + 2. Results matched the boundaries above, including
+the overflow receipt without an increase. Selecting the corpse and pressing
+the shipped E=Use binding verified collection from a zero starting balance.
+Read-only native probes, screenshots and packet logs distinguish actual Use
+from clicks that missed the corpse. The retained `tmp_verify.py` checks 32
+conditions and writes `verification.json`. No browser exceptions occurred;
+the only console errors were 15 connection refusals during intentional server
+restart. Test clients and the temporary server were closed afterward.
diff --git a/docs/corpse-loot.md b/docs/corpse-loot.md
@@ -136,8 +136,9 @@ Failed saves, full inventory, stale sessions and unavailable items retain the
previous owner. Repeated and concurrent requests cannot take the same item
twice. Corpses and untaken contents are currently runtime state; taken inventory
survives reconnect and server restart. Killer-only access is an initial policy:
-public loot rights, team loot, credits and random drops remain separate
-milestones. The level-1 Leet's corpse expiry is described below.
+public loot rights, team loot and random drops remain separate milestones.
+[Corpse credits](corpse-credits.md) describes known-amount cash collection and
+persistence. The level-1 Leet's corpse expiry is described below.
The two-player pickup check exercises the current killer-only policy.
`TestLootConcurrentPlayersHaveOnePersistentOwner` releases two authenticated
diff --git a/server/corpse_credits_test.go b/server/corpse_credits_test.go
@@ -0,0 +1,228 @@
+package main
+
+import (
+ "encoding/binary"
+ "os"
+ "sync"
+ "testing"
+ "time"
+)
+
+func newCorpseCreditWorld(t *testing.T) (*server, *combatTestConn) {
+ t.Helper()
+ world, conn := newCombatWorld()
+ player := world.newCharacter()
+ player.position = [3]float32{}
+ if err := world.saveUser_locked(player); err != nil {
+ t.Fatal(err)
+ }
+ corpse := world.characters[1000000]
+ corpse.health = 0
+ corpse.corpse = &npcCorpse{looter: 1, items: []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Count: 1}}}
+ return world, conn
+}
+
+func TestCorpseCreditsPersistWithoutRepeatingOnReuseOrItemPickup(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, conn := newCorpseCreditWorld(t)
+ player := world.characters[1]
+ player.inventory.Credits = 250
+ world.characters[1000000].corpse.credits = 123
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ conn.packets = nil
+
+ for _, sequence := range []uint32{1, 1, 2, 3} {
+ if err := world.handleLootUse(world.clients[1], lootUseRequest(sequence)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil {
+ t.Fatal(err)
+ }
+ restored := newTestInventoryServer(t).characters[1]
+
+ if player.inventory.Credits != 373 || restored.inventory.Credits != 373 || world.characters[1000000].corpse.credits != 0 ||
+ len(restored.inventory.Items) != 1 || restored.inventory.Items[0].ID != 17 || len(conn.packets) != 7 {
+ t.Fatal("corpse use repeated cash, lost durable credits or broke item pickup")
+ }
+ for _, packet := range conn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e || binary.BigEndian.Uint32(packet[16:20]) == 0x5f4b442a {
+ t.Fatal("an owner cash correction or receipt would race or duplicate native Use")
+ }
+ }
+ packet := fullCharacterPacket(restored)
+ cursor := 64 + len(restored.inventory.Items)*32
+ count := int(binary.BigEndian.Uint32(packet[cursor:])/1009 - 1)
+ values := make(map[uint32]uint32)
+ for offset := cursor + 4; offset < cursor+4+count*8; offset += 8 {
+ values[binary.BigEndian.Uint32(packet[offset:])] = binary.BigEndian.Uint32(packet[offset+4:])
+ }
+ if values[61] != 373 {
+ t.Fatal("reconnect initialization omitted the durable cash balance")
+ }
+}
+
+func TestCorpseCreditsMatchNativeAmountAndBalanceBoundaries(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ starting, credits, want uint32
+ }{
+ {"empty", 250, 0, 250},
+ {"largest ordinary amount", 0, 100000, 100000},
+ {"large amount fallback", 250, 100001, 350},
+ {"negative amount fallback", 250, 0xffffffff, 350},
+ {"exact balance limit", 999999999, 1, 1000000000},
+ {"addition exceeds limit", 999999999, 2, 999999999},
+ {"already at limit", 1000000000, 123, 1000000000},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, _ := newCorpseCreditWorld(t)
+ player := world.characters[1]
+ player.inventory.Credits = scenario.starting
+ world.characters[1000000].corpse.credits = scenario.credits
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+
+ err := world.handleLootUse(world.clients[1], lootUseRequest(1))
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err != nil || player.inventory.Credits != scenario.want || restored.inventory.Credits != scenario.want || world.characters[1000000].corpse.credits != 0 {
+ t.Fatalf("cash diverged from native addition: balance=%d restored=%d err=%v", player.inventory.Credits, restored.inventory.Credits, err)
+ }
+ })
+ }
+}
+
+func TestCorpseCreditsInvalidUseAndFailedSaveRetainCash(t *testing.T) {
+ for _, scenario := range []string{"missing corpse", "expired", "other looter", "unknown corpse", "far", "other zone", "loading", "dead", "foreign owner", "replaced", "failed save"} {
+ t.Run(scenario, func(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, _ := newCorpseCreditWorld(t)
+ player, client, corpse := world.characters[1], world.clients[1], world.characters[1000000]
+ player.inventory.Credits, corpse.corpse.credits = 250, 123
+ if err := world.saveInventory_locked(player, player.inventory); err != nil {
+ t.Fatal(err)
+ }
+ request := lootUseRequest(1)
+ switch scenario {
+ case "missing corpse":
+ delete(world.characters, 1000000)
+ case "expired":
+ corpse.corpse.expiresAt = time.Now().Add(-time.Second)
+ case "other looter":
+ corpse.corpse.looter = 2
+ case "unknown corpse":
+ delete(client.npcs, corpse.id)
+ case "far":
+ corpse.position[0] = 5.125
+ case "other zone":
+ corpse.playfield = 705
+ case "loading":
+ client.loading = true
+ case "dead":
+ player.health = 0
+ case "foreign owner":
+ binary.BigEndian.PutUint32(request[8:12], 2)
+ case "replaced":
+ world.clients[1] = &worldClient{id: 1}
+ case "failed save":
+ os.Remove("data/players/1/inventory.yaml")
+ os.Mkdir("data/players/1/inventory.yaml", 0700)
+ }
+
+ err := world.handleLootUse(client, request)
+
+ if (err != nil) != (scenario == "failed save") || player.inventory.Credits != 250 || corpse.corpse.credits != 123 || client.lootCorpse != 0 {
+ t.Fatalf("rejected use consumed or granted cash: %v", err)
+ }
+ })
+ }
+}
+
+func TestCorpseCreditsCompetingPlayersHaveOnePersistentAward(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, ownerConn := newCorpseCreditWorld(t)
+ world.characters[1000000].corpse.credits = 123
+ competitor := world.newCharacter()
+ competitor.position, competitor.playfield = world.characters[1].position, world.characters[1].playfield
+ competitor.inventory.Credits = 77
+ if err := world.saveUser_locked(competitor); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.saveInventory_locked(competitor, competitor.inventory); err != nil {
+ t.Fatal(err)
+ }
+ competitorConn := &combatTestConn{}
+ world.clients[2] = &worldClient{id: 2, conn: competitorConn, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
+ request := lootUseRequest(1)
+ binary.BigEndian.PutUint32(request[8:12], 2)
+ binary.BigEndian.PutUint32(request[36:40], 2)
+ ownerConn.packets = nil
+ start := make(chan struct{})
+ var workers sync.WaitGroup
+
+ for _, id := range []uint32{1, 1, 1, 2} {
+ workers.Go(func() {
+ <-start
+ body := lootUseRequest(1)
+ if id == 2 {
+ body = request
+ }
+ if err := world.handleLootUse(world.clients[id], body); err != nil {
+ t.Error(err)
+ }
+ })
+ }
+ close(start)
+ workers.Wait()
+ restored := newTestInventoryServer(t)
+
+ if restored.characters[1].inventory.Credits != 123 || restored.characters[2].inventory.Credits != 77 ||
+ world.characters[1000000].corpse.credits != 0 || len(ownerConn.packets) != 2 || len(competitorConn.packets) != 2 {
+ t.Fatal("competing uses duplicated cash, changed the competitor's balance or missed the observer update")
+ }
+ cleared := false
+ for _, packet := range competitorConn.packets {
+ if binary.BigEndian.Uint32(packet[16:20]) == 0x2b333d6e {
+ cleared = binary.BigEndian.Uint32(packet[20:24]) == 51050 && binary.BigEndian.Uint32(packet[24:28]) == 1000000 &&
+ binary.BigEndian.Uint32(packet[29:33]) == 61 && binary.BigEndian.Uint32(packet[33:37]) == 0
+ }
+ }
+ if !cleared {
+ t.Fatal("other observer retained stale corpse cash")
+ }
+}
+
+func TestCorpseCreditsSavedAwardSurvivesClosedOwnerOutput(t *testing.T) {
+ t.Chdir(t.TempDir())
+ world, _ := newCorpseCreditWorld(t)
+ world.characters[1000000].corpse.credits = 123
+ client := world.clients[1]
+ client.writeWake, client.writeClosed = make(chan struct{}, 1), true
+
+ err := world.handleLootUse(client, lootUseRequest(1))
+ restored := newTestInventoryServer(t).characters[1]
+
+ if err == nil || restored.inventory.Credits != 123 || world.characters[1000000].corpse.credits != 0 {
+ t.Fatalf("committed cash award was lost or became repeatable on output failure: %v", err)
+ }
+}
+
+func TestCorpseCreditsRejectOutOfRangePersistentBalance(t *testing.T) {
+ t.Chdir(t.TempDir())
+ newCorpseCreditWorld(t)
+ if err := os.WriteFile("data/players/1/inventory.yaml", []byte("last_id: 0\ncredits: 1000000001\nitems: []\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ world := &server{characters: make(map[uint32]*character)}
+
+ err := world.loadUsers()
+
+ if err == nil {
+ t.Fatal("inventory accepted a balance outside the native range")
+ }
+}
diff --git a/server/inventory.go b/server/inventory.go
@@ -27,6 +27,7 @@ type reclaimItem struct {
type playerInventory struct {
LastID uint32 `yaml:"last_id"`
+ Credits uint32 `yaml:"credits,omitempty"`
Items []ownedItem `yaml:"items"`
Reclaim []reclaimItem `yaml:"reclaim,omitempty"`
Containers map[uint32][]ownedItem `yaml:"containers,omitempty"`
@@ -35,6 +36,9 @@ type playerInventory struct {
}
func (inventory playerInventory) validate() error {
+ if inventory.Credits > 1000000000 {
+ return fmt.Errorf("credit balance exceeds the native limit")
+ }
ids := make(map[uint32]bool)
slots := make(map[uint32]bool)
bags := make(map[uint32]bool)
diff --git a/server/loot.go b/server/loot.go
@@ -11,6 +11,7 @@ import (
type npcCorpse struct {
looter uint32
items []ownedItem
+ credits uint32
expiresAt time.Time
}
@@ -34,7 +35,7 @@ func corpsePacket(character *character) []byte {
// Keep an unlimited use count and an animated model for the remains.
stats := [][2]uint32{{12, 0}, {26, 0xffffffff}, {42, monster.Mesh}, {4, uint32(character.appearance >> 4 & 7)},
{59, uint32(character.appearance >> 7 & 3)}, {89, uint32(character.appearance & 3)},
- {223, 0}, {360, 100}, {415, 50000}, {416, character.id}}
+ {223, 0}, {360, 100}, {415, 50000}, {416, character.id}, {61, character.corpse.credits}}
body = binary.BigEndian.AppendUint32(body, uint32(len(stats)+1)*1009)
for _, stat := range stats {
body = binary.BigEndian.AppendUint32(body, stat[0])
@@ -121,6 +122,31 @@ func (server *server) handleLootUse(client *worldClient, body []byte) error {
return client.send(n3Packet(0x52526858, 50000, client.id, reply))
}
+ // Corpse::Use credits cash after the native success callback, including on close.
+ if corpse.corpse.credits != 0 {
+ credits := corpse.corpse.credits
+ if credits > 100000 {
+ credits = 100
+ }
+ inventory := player.inventory
+ // Mirror the native Cash setter: reject the whole addition above one billion.
+ if credits <= 1000000000-inventory.Credits {
+ inventory.Credits += credits
+ }
+ if err := server.saveInventory_locked(player, inventory); err != nil {
+ return err
+ }
+ corpse.corpse.credits = 0
+
+ // The owner must retain the amount until its deferred Use consumes it locally.
+ body := binary.BigEndian.AppendUint32(nil, 61)
+ body = binary.BigEndian.AppendUint32(body, 0)
+ updates := make(map[*worldClient][][]byte)
+ server.queueCombat_locked(updates, corpse, corpse, n3Packet(0x2b333d6e, 51050, corpse.id, body))
+ delete(updates, client)
+ server.sendCombatUpdates(updates)
+ }
+
// Native Use toggles the same corpse when its window closes.
open := client.lootCorpse != corpse.id
if open && client.lootCorpse != 0 {
diff --git a/server/target_protocol_test.go b/server/target_protocol_test.go
@@ -82,7 +82,7 @@ initialized:
if hex.EncodeToString(npc[60:89]) != "000001cb0b456469746564204e50430000000000000000000000000007" {
t.Fatalf("target NPC appearance, name and new stats: %x", npc[60:89])
}
- if hex.EncodeToString(full[57:73]) != "000003f100007a2f0000003600000001" {
+ if hex.EncodeToString(full[57:73]) != "000003f100007e200000003600000001" {
t.Fatalf("target seventh list and first stat: %x", full[57:73])
}
}
diff --git a/server/world.go b/server/world.go
@@ -164,7 +164,7 @@ func fullCharacterPacket(character *character) []byte {
}
base := character.baseStats()
stats := [][2]uint32{{54, uint32(character.level)}, {4, uint32(character.appearance >> 4 & 7)}, {60, 1}, {33, uint32(character.appearance >> 9 & 3)}, {59, uint32(character.appearance >> 7 & 3)}, {156, 100}, {16, uint32(base.Strength)}, {17, uint32(base.Agility)}, {18, uint32(base.Stamina)}, {19, uint32(base.Intelligence)}, {20, uint32(base.Sense)}, {21, uint32(base.Psychic)}, {27, character.health}, {1, character.maximumHealth()}, {123, uint32(base.FirstAid)}, {124, uint32(base.Treatment)}, {37, character.titleLevel()}}
- stats = append(stats, [2]uint32{51, uint32(character.aggDef)}, [2]uint32{161, uint32(base.ComputerLiteracy)})
+ stats = append(stats, [2]uint32{51, uint32(character.aggDef)}, [2]uint32{161, uint32(base.ComputerLiteracy)}, [2]uint32{61, character.inventory.Credits})
if time.Now().Before(character.implantChangesUntil) {
stats = append(stats, [2]uint32{224, 16})
}