aorecomp

Anarchy Online classic in the browser

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


server/loot_test.go (13113B)


      1 package main
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/binary"
      6 	"encoding/hex"
      7 	"slices"
      8 	"sync"
      9 	"testing"
     10 	"time"
     11 )
     12 
     13 func newLootWorld(t *testing.T) (*server, *combatTestConn) {
     14 	t.Helper()
     15 	world := newTestServer(t)
     16 	// This protocol fixture uses an artificial height-zero origin without terrain.
     17 	world.terrain = nil
     18 	player := world.newCharacter()
     19 	player.position = [3]float32{}
     20 	if err := world.saveUser(player); err != nil {
     21 		t.Fatal(err)
     22 	}
     23 	world.characters = map[uint32]*character{1: player, 1000000: {
     24 		id: 1000000, name: "Leet", playfield: player.playfield, position: [3]float32{1, 0, 0},
     25 		rotation: [4]float32{0, 0, 0, 1}, appearance: 229, monsterData: 17655, npc: true, health: 1,
     26 	}}
     27 	world.mobileNPCs = nil
     28 	conn := &combatTestConn{}
     29 	world.clients[1] = &worldClient{id: 1, conn: conn, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
     30 	if err := world.handleCombat(world.clients[1], attackPacket(1, 1000000)[20:]); err != nil {
     31 		t.Fatal(err)
     32 	}
     33 	world.advanceCombat(player.nextAttack)
     34 	world.characters[1000000].corpse.items = []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Count: 1}}
     35 	return world, conn
     36 }
     37 
     38 func lootUseRequest(sequence uint32) []byte {
     39 	var body []byte
     40 	for _, value := range []uint32{0, sequence, 3, 1, 50000, 1, 51050, 1000000} {
     41 		body = binary.BigEndian.AppendUint32(body, value)
     42 	}
     43 	return n3Packet(0x52526858, 50000, 1, body)[20:]
     44 }
     45 
     46 func lootTakeRequest() []byte {
     47 	var body []byte
     48 	for _, value := range []uint32{107, 0, 50000, 1, 111} {
     49 		body = binary.BigEndian.AppendUint32(body, value)
     50 	}
     51 	return n3Packet(0x47537a24, 50000, 1, body)[20:]
     52 }
     53 
     54 func TestLootNativeCorpseTakeAndRestart(t *testing.T) {
     55 	t.Chdir(t.TempDir())
     56 	world, conn := newLootWorld(t)
     57 	corpse := conn.packets[len(conn.packets)-1]
     58 	animation, _ := hex.DecodeString("000007e20000cf0b000000000000000400000000000000010000000000000000ffffffff0000c76a000f4240000046bb0000000100000000")
     59 	if binary.BigEndian.Uint32(corpse[16:20]) != 0x4f474e05 || !bytes.Contains(corpse, animation) || !bytes.Contains(corpse, []byte("Remains of Leet\x00")) {
     60 		t.Fatalf("native corpse creation: %x", corpse)
     61 	}
     62 	if !bytes.Contains(corpse, []byte{0, 0, 0, 26, 255, 255, 255, 255}) {
     63 		t.Fatal("native Use would consume the corpse")
     64 	}
     65 
     66 	if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil {
     67 		t.Fatal(err)
     68 	}
     69 	if binary.BigEndian.Uint32(conn.packets[len(conn.packets)-1][37:41]) != 0x00030001 {
     70 		t.Fatal("corpse item cannot take the native template-proxy transfer path")
     71 	}
     72 	if err := world.handleInventory(world.clients[1], lootTakeRequest()); err != nil {
     73 		t.Fatal(err)
     74 	}
     75 	restarted := newTestInventoryServer(t)
     76 
     77 	expected := []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}}
     78 	if !slices.Equal(restarted.characters[1].inventory.Items, expected) || restarted.nextItem != 17 || len(world.characters[1000000].corpse.items) != 0 {
     79 		t.Fatalf("loot ownership after restart: %+v", restarted.characters[1].inventory)
     80 	}
     81 	if hex.EncodeToString(conn.packets[len(conn.packets)-1][29:49]) != "0000006b000000000000c3500000000100000030" {
     82 		t.Fatal("pickup acknowledgement lost its corpse source or persisted destination")
     83 	}
     84 	world.handleLootUse(world.clients[1], lootUseRequest(2))
     85 	world.handleLootUse(world.clients[1], lootUseRequest(3))
     86 	if binary.BigEndian.Uint32(conn.packets[len(conn.packets)-1][29:33]) != 1009 {
     87 		t.Fatal("corpse still publishes the taken item")
     88 	}
     89 }
     90 
     91 func TestLootUseTogglesAndRejectsRepeatedSequences(t *testing.T) {
     92 	t.Chdir(t.TempDir())
     93 	world, conn := newLootWorld(t)
     94 	conn.packets = nil
     95 
     96 	world.handleLootUse(world.clients[1], lootUseRequest(1))
     97 	world.handleLootUse(world.clients[1], lootUseRequest(1))
     98 	if world.clients[1].lootCorpse != 1000000 || len(conn.packets) != 2 {
     99 		t.Fatal("repeated use closed or reopened the corpse")
    100 	}
    101 	world.handleLootUse(world.clients[1], lootUseRequest(2))
    102 	if world.clients[1].lootCorpse != 0 || len(conn.packets) != 4 {
    103 		t.Fatal("native close use reopened the loot window")
    104 	}
    105 	if hex.EncodeToString(conn.packets[3][16:45]) != "2049527c0000c76a000f42400000000001000000660000c35000000001" {
    106 		t.Fatalf("close did not unregister the native corpse container: %x", conn.packets[3][16:])
    107 	}
    108 	world.handleLootUse(world.clients[1], lootUseRequest(3))
    109 
    110 	if world.clients[1].lootCorpse != 1000000 || len(conn.packets) != 6 || binary.BigEndian.Uint32(conn.packets[4][29:33]) != 1 || binary.BigEndian.Uint32(conn.packets[4][33:37]) != 3 {
    111 		t.Fatal("reuse did not acknowledge the native status and sequence")
    112 	}
    113 }
    114 
    115 func TestLootFillsTheLastNativeInventorySlot(t *testing.T) {
    116 	t.Chdir(t.TempDir())
    117 	world, conn := newLootWorld(t)
    118 	for slot := uint32(64); slot < 93; slot++ {
    119 		world.characters[1].inventory.Items = append(world.characters[1].inventory.Items,
    120 			ownedItem{ID: slot + 100, Type: 51018, Template: 121567, Quality: 1, Slot: slot, Count: 1})
    121 	}
    122 	world.characters[1].inventory.LastID = 192
    123 	world.handleLootUse(world.clients[1], lootUseRequest(1))
    124 
    125 	err := world.handleInventory(world.clients[1], lootTakeRequest())
    126 	restarted := newTestInventoryServer(t)
    127 
    128 	if err != nil || len(restarted.characters[1].inventory.Items) != 30 ||
    129 		binary.BigEndian.Uint32(conn.packets[len(conn.packets)-1][45:49]) != 77 ||
    130 		len(world.characters[1000000].corpse.items) != 0 {
    131 		t.Fatalf("last-slot pickup failed: %v", err)
    132 	}
    133 	if !slices.Contains(restarted.characters[1].inventory.Items, ownedItem{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 93, Count: 1}) {
    134 		t.Fatalf("last-slot ownership changed: %+v", restarted.characters[1].inventory.Items)
    135 	}
    136 }
    137 
    138 func TestLootRejectsUnavailableItemsWithoutChangingOwnership(t *testing.T) {
    139 	for _, scenario := range []string{"closed", "distance", "playfield", "foreign owner", "stale session", "empty slot", "full inventory", "save failure", "repeat pickup"} {
    140 		t.Run(scenario, func(t *testing.T) {
    141 			t.Chdir(t.TempDir())
    142 			world, _ := newLootWorld(t)
    143 			client := world.clients[1]
    144 			world.handleLootUse(client, lootUseRequest(1))
    145 			request := lootTakeRequest()
    146 			switch scenario {
    147 			case "closed":
    148 				world.handleLootUse(client, lootUseRequest(2))
    149 			case "distance":
    150 				world.characters[1].position[0] = 7
    151 			case "playfield":
    152 				world.characters[1].playfield++
    153 			case "foreign owner":
    154 				world.characters[1000000].corpse.looter = 2
    155 			case "stale session":
    156 				world.clients[1] = &worldClient{id: 1}
    157 			case "empty slot":
    158 				binary.BigEndian.PutUint32(request[20:24], 1)
    159 			case "full inventory":
    160 				for slot := uint32(64); slot < 94; slot++ {
    161 					world.characters[1].inventory.Items = append(world.characters[1].inventory.Items, ownedItem{ID: slot, Type: 51005, Template: 42640, Quality: 1, Slot: slot, Count: 1})
    162 				}
    163 			case "save failure":
    164 				failDatabaseWrites(t, world)
    165 			case "repeat pickup":
    166 				if err := world.handleInventory(client, request); err != nil {
    167 					t.Fatal(err)
    168 				}
    169 			}
    170 			before := append([]ownedItem(nil), world.characters[1].inventory.Items...)
    171 			remaining := append([]ownedItem(nil), world.characters[1000000].corpse.items...)
    172 
    173 			err := world.handleInventory(client, request)
    174 
    175 			if (err != nil) != (scenario == "save failure") || !slices.Equal(before, world.characters[1].inventory.Items) || !slices.Equal(remaining, world.characters[1000000].corpse.items) {
    176 				t.Fatalf("%s changed ownership: %v", scenario, err)
    177 			}
    178 		})
    179 	}
    180 }
    181 
    182 func TestLootSwitchClosesThePreviousContainer(t *testing.T) {
    183 	t.Chdir(t.TempDir())
    184 	world, conn := newLootWorld(t)
    185 	other := *world.characters[1000000]
    186 	other.id = 1000001
    187 	world.characters[other.id] = &other
    188 	world.clients[1].npcs[other.id] = true
    189 	world.handleLootUse(world.clients[1], lootUseRequest(1))
    190 	conn.packets = nil
    191 	request := lootUseRequest(2)
    192 	binary.BigEndian.PutUint32(request[44:48], other.id)
    193 
    194 	err := world.handleLootUse(world.clients[1], request)
    195 
    196 	if err != nil || world.clients[1].lootCorpse != 1000001 || len(conn.packets) != 3 ||
    197 		binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x2049527c ||
    198 		binary.BigEndian.Uint32(conn.packets[0][24:28]) != 1000000 ||
    199 		binary.BigEndian.Uint32(conn.packets[2][16:20]) != 0x4e536976 {
    200 		t.Fatalf("switch did not close the previous container before opening its replacement: %v", err)
    201 	}
    202 }
    203 
    204 func TestLootLateObserverAndInterestReentry(t *testing.T) {
    205 	t.Chdir(t.TempDir())
    206 	world, _ := newLootWorld(t)
    207 	world.characters[2] = &character{id: 2, playfield: world.characters[1].playfield, health: 100}
    208 	conn := &combatTestConn{}
    209 	world.clients[2] = &worldClient{id: 2, conn: conn, target: true, ready: true, npcs: make(map[uint32]bool)}
    210 
    211 	world.advanceNPCs(time.Now())
    212 	world.characters[2].position[0] = 1000
    213 	world.advanceNPCs(time.Now())
    214 	world.characters[2].position[0] = 0
    215 	world.advanceNPCs(time.Now())
    216 
    217 	if len(conn.packets) != 4 || binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x4f474e05 ||
    218 		binary.BigEndian.Uint32(conn.packets[1][20:24]) != 50000 || binary.BigEndian.Uint32(conn.packets[2][20:24]) != 51050 ||
    219 		binary.BigEndian.Uint32(conn.packets[3][16:20]) != 0x4f474e05 {
    220 		t.Fatalf("corpse interest lifecycle: %x", conn.packets)
    221 	}
    222 }
    223 
    224 func TestLootUseRejectsForeignAndUnavailableCorpses(t *testing.T) {
    225 	for _, scenario := range []string{"foreign owner", "distance", "hidden", "living"} {
    226 		t.Run(scenario, func(t *testing.T) {
    227 			t.Chdir(t.TempDir())
    228 			world, conn := newLootWorld(t)
    229 			conn.packets = nil
    230 			switch scenario {
    231 			case "foreign owner":
    232 				world.characters[1000000].corpse.looter = 2
    233 			case "distance":
    234 				world.characters[1].position[0] = 6.01
    235 			case "hidden":
    236 				delete(world.clients[1].npcs, 1000000)
    237 			case "living":
    238 				world.characters[1000000].health = 1
    239 			}
    240 
    241 			err := world.handleLootUse(world.clients[1], lootUseRequest(1))
    242 
    243 			if err != nil || world.clients[1].lootCorpse != 0 || len(conn.packets) != 1 || binary.BigEndian.Uint32(conn.packets[0][29:33]) != 2 {
    244 				t.Fatalf("%s opened or failed to reject corpse use: %v", scenario, err)
    245 			}
    246 		})
    247 	}
    248 }
    249 
    250 func TestLootConcurrentRepeatPickupHasOneOwner(t *testing.T) {
    251 	t.Chdir(t.TempDir())
    252 	world, _ := newLootWorld(t)
    253 	world.handleLootUse(world.clients[1], lootUseRequest(1))
    254 	var workers sync.WaitGroup
    255 	errors := make(chan error, 2)
    256 
    257 	client := world.clients[1]
    258 	zone, stop := startTestZone(t, world)
    259 
    260 	for range 2 {
    261 		workers.Go(func() { errors <- zone.call(zonePacket{client, lootTakeRequest()}) })
    262 	}
    263 	workers.Wait()
    264 	if err := stop(); err != nil {
    265 		t.Fatal(err)
    266 	}
    267 	close(errors)
    268 	restarted := newTestInventoryServer(t)
    269 
    270 	for err := range errors {
    271 		if err != nil {
    272 			t.Fatal(err)
    273 		}
    274 	}
    275 	if len(restarted.characters[1].inventory.Items) != 1 || restarted.characters[1].inventory.Items[0].ID != 17 || len(world.characters[1000000].corpse.items) != 0 {
    276 		t.Fatal("concurrent pickup duplicated or lost the item")
    277 	}
    278 }
    279 
    280 func TestLootConcurrentPlayersHaveOnePersistentOwner(t *testing.T) {
    281 	t.Chdir(t.TempDir())
    282 	world, ownerConn := newLootWorld(t)
    283 	competitor := world.newCharacter()
    284 	competitor.position = world.characters[1].position
    285 	competitor.playfield = world.characters[1].playfield
    286 	if err := world.saveUser(competitor); err != nil {
    287 		t.Fatal(err)
    288 	}
    289 	competitorConn := &combatTestConn{}
    290 	world.clients[2] = &worldClient{id: 2, conn: competitorConn, target: true, ready: true, npcs: map[uint32]bool{1000000: true}}
    291 	if err := world.handleLootUse(world.clients[1], lootUseRequest(1)); err != nil {
    292 		t.Fatal(err)
    293 	}
    294 	ownerConn.packets = nil
    295 	// Even a stale or forged open-container handle cannot grant ownership.
    296 	world.clients[2].lootCorpse = 1000000
    297 	competingRequest := lootTakeRequest()
    298 	binary.BigEndian.PutUint32(competingRequest[8:12], 2)
    299 	binary.BigEndian.PutUint32(competingRequest[28:32], 2)
    300 	start := make(chan struct{})
    301 	errors := make(chan error, 2)
    302 	var workers sync.WaitGroup
    303 
    304 	first, second := world.clients[1], world.clients[2]
    305 	zone, stop := startTestZone(t, world)
    306 
    307 	workers.Go(func() {
    308 		<-start
    309 		errors <- zone.call(zonePacket{first, lootTakeRequest()})
    310 	})
    311 	workers.Go(func() {
    312 		<-start
    313 		errors <- zone.call(zonePacket{second, competingRequest})
    314 	})
    315 	close(start)
    316 	workers.Wait()
    317 	if err := stop(); err != nil {
    318 		t.Fatal(err)
    319 	}
    320 	close(errors)
    321 	restarted := newTestInventoryServer(t)
    322 
    323 	for err := range errors {
    324 		if err != nil {
    325 			t.Fatal(err)
    326 		}
    327 	}
    328 	expected := []ownedItem{{ID: 17, Type: 51005, Template: 42640, Quality: 1, Slot: 64, Count: 1}}
    329 	if !slices.Equal(world.characters[1].inventory.Items, expected) || !slices.Equal(restarted.characters[1].inventory.Items, expected) ||
    330 		len(competitor.inventory.Items) != 0 || len(restarted.characters[2].inventory.Items) != 0 ||
    331 		len(world.characters[1000000].corpse.items) != 0 {
    332 		t.Fatal("competing players duplicated, lost or transferred the item to the wrong owner")
    333 	}
    334 	if len(ownerConn.packets) != 1 || binary.BigEndian.Uint32(ownerConn.packets[0][16:20]) != 0x47537a24 ||
    335 		len(competitorConn.packets) != 2 || binary.BigEndian.Uint32(competitorConn.packets[0][29:33]) != 146 ||
    336 		binary.BigEndian.Uint32(competitorConn.packets[1][16:20]) != 0x2049527c || world.clients[2].lootCorpse != 0 {
    337 		t.Fatal("pickup did not transfer only to the entitled player and close the rejected source")
    338 	}
    339 }