aorecomp

Anarchy Online classic in the browser

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


server/ip_training_test.go (16852B)


      1 package main
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/binary"
      6 	"fmt"
      7 	"slices"
      8 	"sync"
      9 	"testing"
     10 	"time"
     11 )
     12 
     13 func skillTrainingRequest(stats characterStats) []byte {
     14 	body := binary.BigEndian.AppendUint32(nil, 75)
     15 	for _, value := range stats.nativeStats()[1:] {
     16 		body = binary.BigEndian.AppendUint32(body, value[0])
     17 		body = binary.BigEndian.AppendUint32(body, value[1])
     18 	}
     19 	return n3Packet(0x3e205660, 50000, 1, body)
     20 }
     21 
     22 func newTrainingWorld(t *testing.T) (*server, *combatTestConn) {
     23 	t.Helper()
     24 	world, conn := newRangedWorld(t)
     25 	player := world.characters[1]
     26 	player.level = 3
     27 	player.health, player.nano = player.maximumHealth(), player.maximumNano()
     28 	if err := world.saveUser(player); err != nil {
     29 		t.Fatal(err)
     30 	}
     31 	return world, conn
     32 }
     33 
     34 func TestSkillTrainingPricesOriginalTwelveProfessionCosts(t *testing.T) {
     35 	for _, scenario := range []struct {
     36 		profession uint16
     37 		remaining  uint32
     38 	}{
     39 		{1, 1482}, {2, 1437}, {3, 1473}, {4, 1471}, {5, 1467}, {6, 1482},
     40 		{7, 1464}, {8, 1471}, {9, 1446}, {10, 1471}, {11, 1471}, {12, 1456},
     41 	} {
     42 		t.Run(fmt.Sprint(scenario.profession), func(t *testing.T) {
     43 			world, conn := newTrainingWorld(t)
     44 			player := world.characters[1]
     45 			player.profession = scenario.profession
     46 			stats := player.baseStats()
     47 			stats.Ranged.Pistol = 8
     48 			stats.ImprovementPoints = 999999 // Never supplied by the native request.
     49 
     50 			err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:])
     51 			restored := newTestInventoryServer(t).characters[1]
     52 
     53 			if err != nil || player.stats.Ranged.Pistol != 8 || player.stats.ImprovementPoints != scenario.remaining ||
     54 				restored.stats != player.stats || player.inventory.Items[0].Ammo != 3 || player.inventory.Items[1].Count != 100 {
     55 				t.Fatalf("training changed price, persistence or inventory: %+v, %v", player.stats, err)
     56 			}
     57 			if len(conn.packets) != 3 || binary.BigEndian.Uint32(conn.packets[2][29:33]) != 53 ||
     58 				binary.BigEndian.Uint32(conn.packets[2][33:37]) != scenario.remaining {
     59 				t.Fatalf("missing authoritative IP correction: %x", conn.packets)
     60 			}
     61 		})
     62 	}
     63 }
     64 
     65 func TestSkillTrainingAppliesAbilityDependenciesTogetherWithoutFreeHealing(t *testing.T) {
     66 	world, conn := newTrainingWorld(t)
     67 	player := world.characters[1]
     68 	stats := player.baseStats()
     69 	stats.Abilities.Agility, stats.Abilities.Sense = 15, 15
     70 	stats.Abilities.Stamina, stats.Abilities.Psychic = 12, 12
     71 	stats.Body.BodyDevelopment, stats.Body.NanoPool = 7, 7
     72 	stats.Ranged.Pistol = 8
     73 	health, nano := player.health, player.nano
     74 	observer := &combatTestConn{}
     75 	world.characters[2] = &character{id: 2, playfield: 950, health: 100}
     76 	world.clients[2] = &worldClient{id: 2, players: map[uint32]bool{1: true}, conn: observer, target: true, ready: true}
     77 
     78 	err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:])
     79 	restored := newTestInventoryServer(t).characters[1]
     80 
     81 	if err != nil || player.stats.Abilities != stats.Abilities || player.stats.Body != stats.Body ||
     82 		player.stats.Ranged.Pistol != 8 || player.effectiveSkill(112, 8, [6]uint32{0, 60, 0, 0, 40, 0}) != 11 ||
     83 		player.health != health || player.nano != nano || player.maximumHealth() != 55 || player.maximumNano() != 52 ||
     84 		restored.stats != player.stats || restored.health != health || restored.nano != nano {
     85 		t.Fatalf("ability dependency, resource or durable batch mismatch: %+v, %v", player, err)
     86 	}
     87 	var keys []uint32
     88 	for _, packet := range observer.packets {
     89 		keys = append(keys, binary.BigEndian.Uint32(packet[16:20]))
     90 	}
     91 	if !slices.Equal(keys, []uint32{0x2b333d6e, 0x2b333d6e, 0x3e205660}) ||
     92 		binary.BigEndian.Uint32(observer.packets[0][29:33]) != 1 ||
     93 		binary.BigEndian.Uint32(observer.packets[1][29:33]) != 22 || len(conn.packets) != 5 {
     94 		t.Fatalf("observer received wrong shared/private stat updates: %x", keys)
     95 	}
     96 }
     97 
     98 func TestSkillTrainingEnforcesSkillLevelTitleAndAbilityBoundaries(t *testing.T) {
     99 	for _, scenario := range []struct {
    100 		name      string
    101 		level     uint16
    102 		ability   uint16
    103 		from, to  uint16
    104 		remaining uint32
    105 	}{
    106 		{"level1", 1, 600, 9, 10, 1491},
    107 		{"title1", 14, 600, 59, 60, 1441},
    108 		{"title2start", 15, 600, 64, 65, 1436},
    109 		{"title2end", 49, 600, 199, 200, 1301},
    110 		{"title6", 200, 600, 599, 600, 901},
    111 		{"ability", 10, 10, 18, 19, 1482},
    112 	} {
    113 		t.Run(scenario.name, func(t *testing.T) {
    114 			world, conn := newTrainingWorld(t)
    115 			player := world.characters[1]
    116 			player.level = scenario.level
    117 			player.stats.Abilities = characterAbilitiesStats{scenario.ability, scenario.ability, scenario.ability, scenario.ability, scenario.ability, scenario.ability}
    118 			player.stats.Ranged.Pistol = scenario.from
    119 			stats := player.baseStats()
    120 			stats.Ranged.Pistol = scenario.to
    121 
    122 			err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:])
    123 			stats.Ranged.Pistol++
    124 			if err == nil {
    125 				err = world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:])
    126 			}
    127 			restored := newTestInventoryServer(t).characters[1]
    128 
    129 			if err != nil || player.stats.Ranged.Pistol != scenario.to || player.stats.ImprovementPoints != scenario.remaining || restored.stats != player.stats {
    130 				t.Fatalf("cap boundary changed skill or charged rejected point: %+v, %v", player.stats, err)
    131 			}
    132 			if binary.BigEndian.Uint32(conn.packets[len(conn.packets)-1][33:37]) != scenario.remaining {
    133 				t.Fatal("rejected point did not restore the IP display")
    134 			}
    135 		})
    136 	}
    137 }
    138 
    139 func TestSkillTrainingEnforcesBreedAbilityCostsAndCaps(t *testing.T) {
    140 	for _, scenario := range []struct {
    141 		breed     uint16
    142 		level     uint16
    143 		from, to  uint16
    144 		remaining uint32
    145 	}{
    146 		{1, 3, 14, 15, 1472}, {2, 3, 11, 12, 1478},
    147 		{3, 3, 11, 12, 1467}, {4, 3, 23, 24, 1477},
    148 		{1, 200, 471, 472, 558}, {2, 200, 463, 464, 574},
    149 		{3, 200, 463, 464, 111}, {4, 200, 511, 512, 989},
    150 	} {
    151 		t.Run(fmt.Sprintf("breed%d/level%d", scenario.breed, scenario.level), func(t *testing.T) {
    152 			world, _ := newTrainingWorld(t)
    153 			player := world.characters[1]
    154 			player.appearance, player.level = scenario.breed<<4, scenario.level
    155 			player.stats.Abilities.Strength = scenario.from
    156 			stats := player.baseStats()
    157 			stats.Abilities.Strength = scenario.to
    158 
    159 			err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:])
    160 			stats.Abilities.Strength++
    161 			if err == nil {
    162 				err = world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:])
    163 			}
    164 
    165 			if err != nil || player.stats.Abilities.Strength != scenario.to || player.stats.ImprovementPoints != scenario.remaining {
    166 				t.Fatalf("breed ability price/cap mismatch: %+v, %v", player.stats, err)
    167 			}
    168 		})
    169 	}
    170 }
    171 
    172 func TestSkillTrainingUsesProposedAbilitiesAndWornAbilityBonusesForCaps(t *testing.T) {
    173 	for _, scenario := range []string{"proposed abilities", "worn backpack", "stored backpack"} {
    174 		t.Run(scenario, func(t *testing.T) {
    175 			world, _ := newTrainingWorld(t)
    176 			player := world.characters[1]
    177 			player.level = 10
    178 			player.stats.Ranged.Pistol = 19
    179 			stats := player.baseStats()
    180 			stats.Ranged.Pistol = 21
    181 			if scenario == "proposed abilities" {
    182 				stats.Abilities.Agility, stats.Abilities.Sense = 15, 15
    183 			} else {
    184 				slot := uint32(19)
    185 				if scenario == "stored backpack" {
    186 					slot = 65
    187 				}
    188 				player.inventory.Items = append(player.inventory.Items, ownedItem{ID: 3, Type: 51017, Template: 152039, Quality: 1, Count: 1, Slot: slot})
    189 			}
    190 
    191 			err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:])
    192 
    193 			expected := uint16(21)
    194 			if scenario == "stored backpack" {
    195 				expected = 19
    196 			}
    197 			if err != nil || player.stats.Ranged.Pistol != expected {
    198 				t.Fatalf("dependency cap used wrong ability state: %+v, %v", player.stats, err)
    199 			}
    200 		})
    201 	}
    202 }
    203 
    204 func TestSkillTrainingRejectsWholeBatchAndRestoresTentativeStats(t *testing.T) {
    205 	for _, scenario := range []string{"insufficient IP", "decrease", "over cap", "ability cap", "duplicate", "unknown", "negative", "overflow", "wrong owner", "wrong type", "dead", "unsupported breed"} {
    206 		t.Run(scenario, func(t *testing.T) {
    207 			world, conn := newTrainingWorld(t)
    208 			player := world.characters[1]
    209 			stats := player.baseStats()
    210 			stats.Ranged.Pistol = 6
    211 			switch scenario {
    212 			case "insufficient IP":
    213 				player.stats.ImprovementPoints = 4
    214 			case "decrease":
    215 				stats.Body.MartialArts = 4
    216 			case "over cap":
    217 				stats.Body.MartialArts = 1000
    218 			case "ability cap":
    219 				stats.Abilities.Strength = 16
    220 			case "dead":
    221 				player.health = 0
    222 			case "unsupported breed":
    223 				player.appearance = 6 << 4
    224 			}
    225 			request := skillTrainingRequest(stats)[20:]
    226 			switch scenario {
    227 			case "duplicate":
    228 				binary.BigEndian.PutUint32(request[28:32], 16)
    229 			case "unknown":
    230 				binary.BigEndian.PutUint32(request[20:24], 53)
    231 			case "negative":
    232 				binary.BigEndian.PutUint32(request[24:28], 0xffffffff)
    233 			case "overflow":
    234 				binary.BigEndian.PutUint32(request[24:28], 65536)
    235 			case "wrong owner":
    236 				binary.BigEndian.PutUint32(request[8:12], 2)
    237 			case "wrong type":
    238 				binary.BigEndian.PutUint32(request[4:8], 51018)
    239 			}
    240 			if err := world.saveUser(player); err != nil {
    241 				t.Fatal(err)
    242 			}
    243 			before := player.stats
    244 
    245 			err := world.handleSkillTraining(world.clients[1], request)
    246 			restored := newTestInventoryServer(t).characters[1]
    247 
    248 			if err != nil || player.stats != before || restored.stats != before || len(conn.packets) != 2 ||
    249 				binary.BigEndian.Uint32(conn.packets[0][16:20]) != 0x3e205660 ||
    250 				binary.BigEndian.Uint32(conn.packets[1][33:37]) != before.ImprovementPoints {
    251 				t.Fatalf("rejected batch changed state or lost correction: %+v, %v", player.stats, err)
    252 			}
    253 		})
    254 	}
    255 }
    256 
    257 func TestSkillTrainingRejectsMalformedSnapshotsAndInactiveSessions(t *testing.T) {
    258 	for _, scenario := range []string{"short", "long", "count", "unready", "loading", "replaced"} {
    259 		t.Run(scenario, func(t *testing.T) {
    260 			world, conn := newTrainingWorld(t)
    261 			player, client := world.characters[1], world.clients[1]
    262 			before := player.stats
    263 			stats := before
    264 			stats.Ranged.Pistol = 6
    265 			request := skillTrainingRequest(stats)[20:]
    266 			malformed := true
    267 			switch scenario {
    268 			case "short":
    269 				request = request[:len(request)-1]
    270 			case "long":
    271 				request = append(request, 0)
    272 			case "count":
    273 				binary.BigEndian.PutUint32(request[16:20], 74)
    274 			case "unready":
    275 				client.ready, malformed = false, false
    276 			case "loading":
    277 				client.loading, malformed = true, false
    278 			case "replaced":
    279 				world.clients[1], malformed = &worldClient{id: 1}, false
    280 			}
    281 
    282 			err := world.handleSkillTraining(client, request)
    283 
    284 			if (err != nil) != malformed || player.stats != before || len(conn.packets) != 0 {
    285 				t.Fatalf("invalid snapshot/session changed state: %v", err)
    286 			}
    287 		})
    288 	}
    289 }
    290 
    291 func TestSkillTrainingRepeatedConcurrentAcceptChargesOnce(t *testing.T) {
    292 	world, _ := newTrainingWorld(t)
    293 	player := world.characters[1]
    294 	player.stats.ImprovementPoints = 5
    295 	stats := player.baseStats()
    296 	stats.Ranged.Pistol = 6
    297 	request := skillTrainingRequest(stats)[20:]
    298 	var calls sync.WaitGroup
    299 	client := world.clients[1]
    300 	zone, stop := startTestZone(t, world)
    301 
    302 	for range 8 {
    303 		calls.Go(func() {
    304 			if err := zone.call(zonePacket{client, request}); err != nil {
    305 				t.Error(err)
    306 			}
    307 		})
    308 	}
    309 
    310 	calls.Wait()
    311 	if err := stop(); err != nil {
    312 		t.Fatal(err)
    313 	}
    314 	restored := newTestInventoryServer(t).characters[1]
    315 
    316 	if player.stats.Ranged.Pistol != 6 || player.stats.ImprovementPoints != 0 || restored.stats != player.stats {
    317 		t.Fatalf("repeated accept charged twice or lost exact balance: %+v", player.stats)
    318 	}
    319 }
    320 
    321 func TestSkillTrainingSaveFailurePublishesNothing(t *testing.T) {
    322 	world, conn := newTrainingWorld(t)
    323 	player := world.characters[1]
    324 	before := player.stats
    325 	stats := before
    326 	stats.Abilities.Agility, stats.Ranged.Pistol = 12, 8
    327 	if _, err := world.db.Exec("CREATE TRIGGER fail_training BEFORE UPDATE OF improvement_points ON characters BEGIN SELECT RAISE(FAIL, 'test training failure'); END"); err != nil {
    328 		t.Fatal(err)
    329 	}
    330 
    331 	err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:])
    332 	restored := newTestInventoryServer(t).characters[1]
    333 
    334 	if err == nil || player.stats != before || restored.stats != before || len(conn.packets) != 0 {
    335 		t.Fatal("failed training transaction changed stats, IP or client state")
    336 	}
    337 }
    338 
    339 func TestSkillTrainingPricesLargeIPBalancesWithoutFloatRounding(t *testing.T) {
    340 	world, _ := newTrainingWorld(t)
    341 	player := world.characters[1]
    342 	player.stats.ImprovementPoints = 16777217
    343 	stats := player.stats
    344 	stats.Ranged.Pistol = 6
    345 
    346 	err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:])
    347 
    348 	if err != nil || player.stats.ImprovementPoints != 16777212 || player.stats.Ranged.Pistol != 6 {
    349 		t.Fatalf("large balance changed the point price: %+v, %v", player.stats, err)
    350 	}
    351 }
    352 
    353 func TestSkillTrainingRoundsFractionalCostOncePerAcceptedBatch(t *testing.T) {
    354 	for _, scenario := range []struct {
    355 		ip             uint32
    356 		both, accepted bool
    357 	}{
    358 		{7, false, false}, {8, false, true}, {15, true, true},
    359 	} {
    360 		t.Run(fmt.Sprintf("ip%d/both%t", scenario.ip, scenario.both), func(t *testing.T) {
    361 			world, _ := newTrainingWorld(t)
    362 			player := world.characters[1]
    363 			player.profession, player.stats.ImprovementPoints = 3, scenario.ip
    364 			stats := player.stats
    365 			stats.Ranged.Pistol = 6
    366 			if scenario.both {
    367 				stats.Speed.NanoResist = 6
    368 			}
    369 
    370 			err := world.handleSkillTraining(world.clients[1], skillTrainingRequest(stats)[20:])
    371 
    372 			if err != nil {
    373 				t.Fatal(err)
    374 			}
    375 			if scenario.accepted {
    376 				if player.stats.Ranged.Pistol != 6 || player.stats.ImprovementPoints != 0 {
    377 					t.Fatalf("wrong fractional batch charge: %+v", player.stats)
    378 				}
    379 			} else if player.stats.Ranged.Pistol != 5 || player.stats.ImprovementPoints != 7 {
    380 				t.Fatalf("fractional price admitted insufficient balance: %+v", player.stats)
    381 			}
    382 		})
    383 	}
    384 }
    385 
    386 func TestSkillTrainingDispatchesNativeSnapshotThroughWorldConnection(t *testing.T) {
    387 	world, _ := newTrainingWorld(t)
    388 	world.clients[1].conn = &combatInterestConn{}
    389 	stats := world.characters[1].stats
    390 	stats.Ranged.Pistol = 6
    391 	cookie := systemPacket(0x1b, []byte{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})
    392 	input := append(cookie, n3Packet(0x570c2039, 50000, 1, nil)...)
    393 	input = append(input, skillTrainingRequest(stats)...)
    394 	conn := &combatInterestConn{input: bytes.NewReader(input)}
    395 
    396 	shutdown := startTestService(t, world)
    397 	err := world.serveWorldClient(&worldClient{conn: conn, loading: true})
    398 
    399 	if err := shutdown(); err != nil {
    400 		t.Fatal(err)
    401 	}
    402 	restored := newTestInventoryServer(t)
    403 	if err != nil || restored.characters[1].stats.Ranged.Pistol != 6 || restored.characters[1].stats.ImprovementPoints != 1495 {
    404 		t.Fatalf("native training dispatcher failed: %+v, %v", restored.characters[1].stats, err)
    405 	}
    406 }
    407 
    408 func TestSkillTrainingAnchorsHeldMovementBeforeRunSpeedChange(t *testing.T) {
    409 	world, _ := newTrainingWorld(t)
    410 	player, client := world.characters[1], world.clients[1]
    411 	player.level, player.running = 100, true
    412 	player.stats.Abilities = characterAbilitiesStats{100, 100, 100, 100, 100, 100}
    413 	player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1}
    414 	player.health = player.maximumHealth()
    415 	world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, time.Now().Add(-time.Second))
    416 	stats := player.stats
    417 	stats.Speed.RunSpeed = 101
    418 
    419 	err := world.handleSkillTraining(client, skillTrainingRequest(stats)[20:])
    420 	position := predictedPosition(player, world.characters[client.id].movement.updatedAt.Add(time.Second))
    421 
    422 	if err != nil || player.stats.Speed.RunSpeed != 101 || player.position[2] < 4.4 || player.position[2] > 4.8 ||
    423 		position[2]-player.position[2] < 4.504 || position[2]-player.position[2] > 4.506 {
    424 		t.Fatalf("training retroactively applied new run speed: %v -> %v, %v", player.position, position, err)
    425 	}
    426 }
    427 
    428 func TestSkillTrainingAnchorsLowHealthMovementBeforeMaximumHealthChanges(t *testing.T) {
    429 	world, _ := newTrainingWorld(t)
    430 	player, client := world.characters[1], world.clients[1]
    431 	player.level, player.running = 100, true
    432 	player.stats.Abilities = characterAbilitiesStats{100, 100, 100, 100, 100, 100}
    433 	player.position, player.rotation = [3]float32{}, [4]float32{0, 0, 0, 1}
    434 	player.health = 100
    435 	world.characters[client.id].movement = heldPlayerMovement(world.characters[client.id], 1, time.Now().Add(-time.Second))
    436 	stats := player.stats
    437 	stats.Body.BodyDevelopment = 6
    438 
    439 	err := world.handleSkillTraining(client, skillTrainingRequest(stats)[20:])
    440 	position := predictedPosition(player, world.characters[client.id].movement.updatedAt.Add(time.Second))
    441 
    442 	if err != nil || player.stats.Body.BodyDevelopment != 6 || player.maximumHealth() != 1000 ||
    443 		player.position[2] < 3.506 || player.position[2] > 3.7 ||
    444 		position[2]-player.position[2] < 3.499 || position[2]-player.position[2] > 3.501 {
    445 		t.Fatalf("training changed the previous low-health movement segment: %v -> %v, %v", player.position, position, err)
    446 	}
    447 }