server/nano_health_drain_test.go (16701B)
1 package main 2 3 import ( 4 "ao/server/gamedata" 5 "bytes" 6 _ "embed" 7 "encoding/binary" 8 "encoding/json" 9 "fmt" 10 "slices" 11 "testing" 12 "time" 13 ) 14 15 //go:embed testdata/health-drain-nanos.json 16 var healthDrainNanoData []byte 17 18 type healthDrainFixture struct { 19 Program, Crystal, Quality, Damage, Healing uint32 20 Cost, Debit, Attack, Recharge, Range uint32 21 TargetMaximum uint32 22 } 23 24 func healthDrainFixtures(t *testing.T) []healthDrainFixture { 25 t.Helper() 26 var fixtures []healthDrainFixture 27 if err := json.Unmarshal(healthDrainNanoData, &fixtures); err != nil { 28 t.Fatal(err) 29 } 30 return fixtures 31 } 32 33 func TestHealthDrainCatalogMatchesCompleteOriginalContracts(t *testing.T) { 34 fixtures := healthDrainFixtures(t) 35 var expectedPrograms, expectedCrystals, programs, crystals []uint32 36 for _, fixture := range fixtures { 37 expectedPrograms = append(expectedPrograms, fixture.Program) 38 expectedCrystals = append(expectedCrystals, fixture.Crystal) 39 } 40 41 for program := range gamedata.NanoTemplates { 42 if directDamageNano(program) != nil && damageNanoCasterHealing(program) != nil { 43 programs = append(programs, program) 44 } 45 } 46 for crystal := range gamedata.ItemTemplates { 47 if program := nanoCrystalProgram(crystal); directDamageNano(program) != nil && damageNanoCasterHealing(program) != nil { 48 crystals = append(crystals, crystal) 49 } 50 } 51 for _, values := range [][]uint32{expectedPrograms, expectedCrystals, programs, crystals} { 52 slices.Sort(values) 53 } 54 55 if len(fixtures) != 30 || !slices.Equal(expectedPrograms, programs) || !slices.Equal(expectedCrystals, crystals) { 56 t.Fatal("health-drain admission differs from the complete original census", programs, crystals) 57 } 58 for _, fixture := range fixtures { 59 hit, heal := directDamageNano(fixture.Program), damageNanoCasterHealing(fixture.Program) 60 if uint32(-*hit.Arguments[1].Integer) != fixture.Damage || uint32(-*hit.Arguments[2].Integer) != fixture.Damage || 61 uint32(*hit.Arguments[3].Integer) != 92 || uint32(*heal.Arguments[1].Integer) != fixture.Healing || 62 uint32(*heal.Arguments[2].Integer) != fixture.Healing || nanoStat(fixture.Program, 407) != fixture.Cost || 63 nanoStat(fixture.Program, 294) != fixture.Attack || nanoStat(fixture.Program, 210) != fixture.Recharge || 64 nanoStat(fixture.Program, 287) != fixture.Range { 65 t.Fatal("authored health-drain effects or metadata changed", fixture.Program) 66 } 67 } 68 } 69 70 func TestHealthDrainCrystalsLearnCastAndRetainBothOutcomes(t *testing.T) { 71 for _, fixture := range healthDrainFixtures(t) { 72 t.Run(fmt.Sprint(fixture.Program), func(t *testing.T) { 73 world, _ := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: fixture.Crystal, Profession: 7}) 74 player, target, client := world.characters[1], world.characters[1000000], world.clients[1] 75 player.health = 1 76 if err := world.savePosition(player); err != nil { 77 t.Fatal(err) 78 } 79 original := gamedata.NPCCombatProfiles[17655][1] 80 profile := *original 81 profile.Health = 1000 82 gamedata.NPCCombatProfiles[17655][1] = &profile 83 t.Cleanup(func() { gamedata.NPCCombatProfiles[17655][1] = original }) 84 target.health, target.combatProfile = 1000, &profile 85 if err := world.flushWorld(); err != nil { 86 t.Fatal(err) 87 } 88 if player.inventory.Items[0].Quality != fixture.Quality { 89 t.Fatal("original crystal quality changed") 90 } 91 92 if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { 93 t.Fatal(err) 94 } 95 if !slices.Equal(player.inventory.LearnedNanos, []uint32{fixture.Program}) || len(player.inventory.Items) != 0 { 96 t.Fatal("complete drain crystal did not upload") 97 } 98 if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, fixture.Program})[20:]); err != nil || client.nanoCast == nil { 99 t.Fatal("complete drain did not start", err) 100 } 101 at := client.nanoCast.readyAt.Add(time.Nanosecond) 102 world.advanceNanos(at) 103 world.advanceNanos(at.Add(time.Nanosecond)) 104 cold := newTestInventoryServer(t) 105 106 if player.health != 1+fixture.Healing || target.health != 1000-fixture.Damage || player.nano != 50000-fixture.Debit || 107 player.nanoReserved != 0 || client.nanoCast != nil || !slices.Equal(player.inventory.LearnedNanos, []uint32{fixture.Program}) || 108 cold.characters[1].health != player.health || cold.characters[1].nano != player.nano || 109 cold.characters[1000000].health != target.health || !cold.characters[1].nanoRechargeUntil.Equal(player.nanoRechargeUntil) || 110 player.savedVitals.Health != player.health || len(player.inventory.Items) != 0 || 111 player.fighting != 0 || target.fighting != 1 || len(target.activeNanos) != 0 { 112 t.Fatal("health drain lost a complete effect, cost, recharge or learned state", fixture.Program, player.health, player.nano, target.health) 113 } 114 }) 115 } 116 } 117 118 func TestHealthDrainStartupUploadsAndCastsBothHits(t *testing.T) { 119 world, _ := newNanoCastingWorld(t) 120 player, target, client := world.characters[1], world.characters[1000000], world.clients[1] 121 player.profession, player.level, player.health, player.nano = 7, 2, 1, 30 122 player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.TimeAndSpace = 5, 7 123 player.inventory.LearnedNanos = nil 124 if err := world.saveUser(player); err != nil { 125 t.Fatal(err) 126 } 127 if granted, err := world.grantItem(player, 78417); err != nil || !granted { 128 t.Fatal(granted, err) 129 } 130 131 if err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]); err != nil { 132 t.Fatal(err) 133 } 134 if !slices.Equal(player.inventory.LearnedNanos, []uint32{76742}) || len(player.inventory.Items) != 0 { 135 t.Fatal("eligible Trader startup crystal did not upload its complete health-drain program") 136 } 137 if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 76742})[20:]); err != nil || client.nanoCast == nil { 138 t.Fatal("learned health drain did not start", err) 139 } 140 world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) 141 cold := newTestInventoryServer(t) 142 143 if player.health != 5 || player.nano != 15 || player.nanoReserved != 0 || target.health != 90 || client.nanoCast != nil || 144 cold.characters[1].health != 5 || cold.characters[1].nano != 15 || cold.characters[1000000].health != 90 || 145 !cold.characters[1].nanoRechargeUntil.Equal(player.nanoRechargeUntil) || !slices.Equal(cold.characters[1].inventory.LearnedNanos, []uint32{76742}) { 146 t.Fatal("health drain did not atomically retain healing, damage, cost, recharge and learning", player.health, player.nano, target.health) 147 } 148 } 149 150 func TestHealthDrainClampsBothHitsAndKeepsTargetRequirementsScoped(t *testing.T) { 151 for _, scenario := range []string{"target equality", "target passes", "lethal", "full caster", "partial healing", "missing target"} { 152 t.Run(scenario, func(t *testing.T) { 153 world, _ := newNanoCastingWorld(t) 154 player, target, client := world.characters[1], world.characters[1000000], world.clients[1] 155 player.profession, player.health, player.nano = 7, 1, 30 156 player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.TimeAndSpace = 5, 7 157 player.inventory.LearnedNanos = []uint32{76742} 158 profile := *gamedata.NPCCombatProfiles[17655][1] 159 target.combatProfile = &profile 160 if scenario == "target equality" { 161 profile.Health, target.health = 9, 9 162 } else if scenario == "target passes" { 163 profile.Health, target.health = 10, 10 164 } else if scenario == "lethal" { 165 target.health = 1 166 } else if scenario == "full caster" { 167 player.health = player.maximumHealth() 168 } else if scenario == "partial healing" { 169 player.health = player.maximumHealth() - 2 170 } 171 if err := world.saveUser(player); err != nil { 172 t.Fatal(err) 173 } 174 request := characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 76742})[20:] 175 if scenario == "missing target" { 176 binary.BigEndian.PutUint32(request[24:28], 999999) 177 } 178 before := player.health 179 180 err := world.handleNanoCast(client, request) 181 started := client.nanoCast != nil 182 if started { 183 world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) 184 } 185 186 if err != nil { 187 t.Fatal(err) 188 } 189 if scenario == "target equality" || scenario == "missing target" { 190 if started || player.health != before || player.nano != 30 || player.nanoReserved != 0 { 191 t.Fatal("invalid target bypassed the scoped requirement or charged the caster") 192 } 193 return 194 } 195 if !started || player.health != min(player.maximumHealth(), before+4) || player.nano != 15 || 196 (scenario == "lethal" || scenario == "target passes") && target.health != 0 { 197 t.Fatal("drain did not clamp its independent authored hits", player.health, target.health) 198 } 199 }) 200 } 201 } 202 203 func TestHealthDrainFailedOutcomeRollsBackBothRecipients(t *testing.T) { 204 for _, phase := range []string{"healing", "ignored healing", "NPC", "ignored NPC", "commit"} { 205 t.Run(phase, func(t *testing.T) { 206 world, output := newNanoCastingWorld(t) 207 player, target, client := world.characters[1], world.characters[1000000], world.clients[1] 208 player.profession, player.health, player.nano = 7, 1, 30 209 player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.TimeAndSpace = 5, 7 210 player.inventory.LearnedNanos = []uint32{76742} 211 if err := world.saveUser(player); err != nil { 212 t.Fatal(err) 213 } 214 if err := world.flushWorld(); err != nil { 215 t.Fatal(err) 216 } 217 request := characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 76742})[20:] 218 if err := world.handleNanoCast(client, request); err != nil || client.nanoCast == nil { 219 t.Fatal("drain admission failed", err) 220 } 221 at := client.nanoCast.readyAt.Add(time.Nanosecond) 222 statement := "CREATE TRIGGER fail_drain BEFORE UPDATE OF health ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(FAIL, 'healing'); END" 223 switch phase { 224 case "ignored healing": 225 statement = "CREATE TRIGGER fail_drain BEFORE UPDATE OF health ON characters WHEN NEW.id=1 BEGIN SELECT RAISE(IGNORE); END" 226 case "NPC": 227 statement = "CREATE TRIGGER fail_drain BEFORE UPDATE ON npcs BEGIN SELECT RAISE(FAIL, 'NPC'); END" 228 case "ignored NPC": 229 statement = "CREATE TRIGGER fail_drain BEFORE UPDATE ON npcs BEGIN SELECT RAISE(IGNORE); END" 230 case "commit": 231 statement = "CREATE TABLE pending_drain (player_id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_drain AFTER UPDATE OF health ON characters WHEN NEW.id=1 BEGIN INSERT INTO pending_drain VALUES (999999); END" 232 } 233 if _, err := world.db.Exec(statement); err != nil { 234 t.Fatal(err) 235 } 236 output.packets = nil 237 238 world.advanceNanos(at) 239 cold := newTestInventoryServer(t) 240 241 if player.health != 1 || player.nano != 30 || player.nanoReserved != 0 || target.health != 100 || client.nanoCast != nil || 242 !player.nanoRechargeUntil.IsZero() || cold.characters[1].health != 1 || cold.characters[1].nano != 30 || cold.characters[1000000].health != 100 { 243 t.Fatal("failed drain published or retained a partial heal, damage, cost or recharge") 244 } 245 for _, packet := range output.packets { 246 if bytes.Equal(packet[16:20], []byte{0x47, 0x27, 0x21, 0x3e}) || 247 binary.BigEndian.Uint32(packet[16:20]) == 0x5e477770 && binary.BigEndian.Uint32(packet[29:33]) == 107 { 248 t.Fatal("failed drain sent a result before its complete transaction") 249 } 250 } 251 if _, err := world.db.Exec("DROP TRIGGER fail_drain"); err != nil { 252 t.Fatal(err) 253 } 254 if err := world.handleNanoCast(client, request); err != nil || client.nanoCast == nil { 255 t.Fatal("drain could not retry", err) 256 } 257 world.advanceNanos(client.nanoCast.readyAt.Add(time.Nanosecond)) 258 cold = newTestInventoryServer(t) 259 if player.health != 5 || player.nano != 15 || target.health != 90 || cold.characters[1].health != 5 || cold.characters[1000000].health != 90 { 260 t.Fatal("drain retry did not commit exactly one full paired outcome") 261 } 262 }) 263 } 264 } 265 266 func TestHealthDrainRejectsPartialOrUnverifiedPairs(t *testing.T) { 267 for _, scenario := range []string{"missing heal", "missing damage", "extra effect", "reversed effects", "other heal resource", "other heal target", "conditional heal", "periodic heal", "periodic damage", "opaque healing", "reversed healing", "positive damage", "unknown target criterion"} { 268 t.Run(scenario, func(t *testing.T) { 269 world, output := newDirectDamageWorld(t, directDamageNanoFixture{Crystal: 78417, Profession: 7}) 270 player, target, client := world.characters[1], world.characters[1000000], world.clients[1] 271 player.health = 1 272 original := gamedata.NanoTemplates[76742] 273 definition := *original 274 definition.Sections = slices.Clone(original.Sections) 275 functions := slices.Clone(*definition.Sections[2].Functions) 276 functions[0].Arguments = slices.Clone(functions[0].Arguments) 277 functions[1].Arguments = slices.Clone(functions[1].Arguments) 278 switch scenario { 279 case "missing heal": 280 functions = functions[1:] 281 case "missing damage": 282 functions = functions[:1] 283 case "extra effect": 284 functions = append(functions, gamedata.ItemFunction{ID: 53051}) 285 case "reversed effects": 286 functions[0], functions[1] = functions[1], functions[0] 287 case "other heal resource": 288 value := int32(214) 289 functions[0].Arguments[0].Integer = &value 290 case "other heal target": 291 functions[0].Target = 2 292 case "conditional heal": 293 functions[0].Requirements = []gamedata.ItemRequirement{{Stat: 54, Value: 20, Operator: 2}} 294 case "periodic heal": 295 functions[0].TickCount = 2 296 case "periodic damage": 297 functions[1].TickCount = 2 298 case "opaque healing": 299 functions[0].Arguments[1].Integer = nil 300 case "reversed healing": 301 value := int32(3) 302 functions[0].Arguments[2].Integer = &value 303 case "positive damage": 304 value := int32(10) 305 functions[1].Arguments[1].Integer = &value 306 case "unknown target criterion": 307 actions := slices.Clone(*definition.Sections[3].Actions) 308 actions[0].Requirements = slices.Clone(actions[0].Requirements) 309 actions[0].Requirements[len(actions[0].Requirements)-2].Stat = 455 310 definition.Sections[3].Actions = &actions 311 } 312 definition.Sections[2].Functions = &functions 313 gamedata.NanoTemplates[76742] = &definition 314 t.Cleanup(func() { gamedata.NanoTemplates[76742] = original }) 315 316 err := world.handleOwnedItemUse(client, backpackUseRequest(1, 64, 1)[20:]) 317 if len(player.inventory.LearnedNanos) != 0 { 318 t.Fatal("partial health-drain contract uploaded") 319 } 320 player.inventory.LearnedNanos = []uint32{76742} 321 if err == nil { 322 err = world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 76742})[20:]) 323 } 324 325 if err != nil || client.nanoCast != nil || player.health != 1 || player.nano != 50000 || target.health != 100 || 326 len(player.inventory.Items) != 1 || len(output.packets) != 2 || binary.BigEndian.Uint32(output.packets[0][29:33]) != 2 || 327 binary.BigEndian.Uint32(output.packets[1][29:33]) != 108 { 328 t.Fatal("unsupported pair consumed a crystal, healed or damaged a recipient, or reserved a cost", err) 329 } 330 }) 331 } 332 } 333 334 func TestHealthDrainCancelledOrUnavailableTargetAppliesNeitherHit(t *testing.T) { 335 for _, scenario := range []string{"cancel", "range", "target death"} { 336 t.Run(scenario, func(t *testing.T) { 337 world, _ := newNanoCastingWorld(t) 338 player, target, client := world.characters[1], world.characters[1000000], world.clients[1] 339 player.profession, player.health, player.nano = 7, 1, 30 340 player.stats.NanoAiding.BiologicalMetamorphosis, player.stats.NanoAiding.TimeAndSpace = 5, 7 341 player.inventory.LearnedNanos = []uint32{76742} 342 if err := world.saveUser(player); err != nil { 343 t.Fatal(err) 344 } 345 if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{19, 50000, target.id, 53019, 76742})[20:]); err != nil || client.nanoCast == nil { 346 t.Fatal("drain admission failed", err) 347 } 348 at := client.nanoCast.readyAt.Add(time.Nanosecond) 349 if scenario == "range" { 350 target.position[0] += 100 351 } else if scenario == "target death" { 352 target.health = 0 353 } 354 before := target.health 355 356 if scenario == "cancel" { 357 if err := world.handleNanoCast(client, characterActionPacket(1, [5]uint32{108})[20:]); err != nil { 358 t.Fatal(err) 359 } 360 } 361 world.advanceNanos(at) 362 world.advanceNanos(at.Add(time.Second)) 363 cold := newTestInventoryServer(t).characters[1] 364 365 if player.health != 1 || player.nano != 30 || player.nanoReserved != 0 || client.nanoCast != nil || target.health != before || 366 !player.nanoRechargeUntil.IsZero() || cold.health != 1 || cold.nano != 30 { 367 t.Fatal("cancelled drain applied one hit or retained a cost/recharge") 368 } 369 }) 370 } 371 }