aorecomp

Anarchy Online classic in the browser

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


server/mission_key_copy_test.go (12583B)


      1 package main
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/binary"
      6 	"net"
      7 	"reflect"
      8 	"slices"
      9 	"sync"
     10 	"testing"
     11 	"time"
     12 )
     13 
     14 func newMissionKeyCopyWorld(t *testing.T) (*server, *combatTestConn) {
     15 	t.Helper()
     16 	world, output := newAcceptedMissionWorld(t)
     17 	if granted, err := world.grantItem(world.characters[1], 28564); err != nil || !granted {
     18 		t.Fatal(granted, err)
     19 	}
     20 	output.packets = nil
     21 	return world, output
     22 }
     23 
     24 func TestMissionKeyCopyNativeDispatchAndColdEntryWithoutOriginal(t *testing.T) {
     25 	newMissionKeyCopyWorld(t)
     26 	world := reloadMissionEntranceWorld(t)
     27 	shutdown := startTestService(t, world)
     28 	connection := connectZoningClient(t, world, true)
     29 	defer connection.Close()
     30 
     31 	if _, err := connection.Write(targetPacket(characterActionPacket(1, [5]uint32{81, 104, 66, 104, 65}))); err != nil {
     32 		t.Fatal(err)
     33 	}
     34 	addition, err := readPacket(connection)
     35 	if err != nil {
     36 		t.Fatal(err)
     37 	}
     38 	originalPlayfield := testPlayerData(t, world, 1).Playfield
     39 	if err := shutdown(); err != nil {
     40 		t.Fatal(err)
     41 	}
     42 	cold := reloadMissionEntranceWorld(t)
     43 	player := cold.characters[1]
     44 	client := &worldClient{id: 1, target: true, ready: true, conn: &combatTestConn{}}
     45 	cold.clients[1] = client
     46 	if err := cold.handleInventory(client, characterActionPacket(1, [5]uint32{112, 104, 65, 28577, 28577})[20:]); err != nil {
     47 		t.Fatal(err)
     48 	}
     49 	player.geometry = cold.geometry
     50 	player.position, player.rotation = [3]float32{89.30216, 115.75, 152.5}, [4]float32{0, 1, 0, 0}
     51 	if err := cold.handleMovement(client, playerMovementRequest(player, 1)); err != nil {
     52 		t.Fatal(err)
     53 	}
     54 	restored := reloadMissionEntranceWorld(t)
     55 	var key, binding uint32
     56 	err = restored.db.QueryRow("SELECT item_id,mission_id FROM mission_keys").Scan(&key, &binding)
     57 
     58 	if err != nil || key != 4 || binding != 2 || restored.characters[1].playfield != 65536 ||
     59 		originalPlayfield != 3000 || restored.nextItem != 5 || restored.characters[1].inventory.Credits != 4 ||
     60 		!slices.Equal(restored.characters[1].inventory.Items, []ownedItem{
     61 			{ID: 1, Type: 51018, Template: 209283, Quality: 1, Slot: 64, Count: 1},
     62 			{ID: 3, Type: 51054, Template: 28564, Quality: 1, Slot: 66, Count: 1},
     63 			{ID: 4, Type: 51053, Template: 28577, Quality: 1, Slot: 67, Count: 1}}) {
     64 		t.Fatalf("copy admission: key=%d binding=%d world=%d originalWorld=%d next=%d cash=%d items=%+v error=%v", key, binding,
     65 			restored.characters[1].playfield, originalPlayfield, restored.nextItem, restored.characters[1].inventory.Credits,
     66 			restored.characters[1].inventory.Items, err)
     67 	}
     68 	if len(addition) != 45 || binary.BigEndian.Uint32(addition[16:20]) != 0x052e2f0c ||
     69 		!bytes.Equal(addition[29:45], []byte{0, 0, 111, 161, 0, 0, 111, 161, 0, 0, 0, 1, 0, 0, 0, 1}) {
     70 		t.Fatal("native dispatch did not publish one QL1 key after its binding committed")
     71 	}
     72 }
     73 
     74 func TestMissionKeyCopyRejectsUnsupportedInputsAndUnavailableAssignments(t *testing.T) {
     75 	for _, scenario := range []string{"tool type", "tool quality", "tool count", "key type", "key template", "key quality", "key count", "unbound", "expired", "completed", "full inventory", "banked key", "reclaimed key"} {
     76 		t.Run(scenario, func(t *testing.T) {
     77 			world, output := newMissionKeyCopyWorld(t)
     78 			player := world.characters[1]
     79 			request := combinationRequest(1, 66, 65)
     80 			switch scenario {
     81 			case "tool type":
     82 				player.inventory.Items[2].Type = 51005
     83 			case "tool quality":
     84 				player.inventory.Items[2].Quality = 2
     85 			case "tool count":
     86 				player.inventory.Items[2].Count = 2
     87 			case "key type":
     88 				player.inventory.Items[1].Type = 51005
     89 			case "key template":
     90 				player.inventory.Items[1].Template = 95577
     91 			case "key quality":
     92 				player.inventory.Items[1].Quality = 2
     93 			case "key count":
     94 				player.inventory.Items[1].Count = 2
     95 			case "unbound":
     96 				if _, err := world.db.Exec("DELETE FROM mission_keys"); err != nil {
     97 					t.Fatal(err)
     98 				}
     99 			case "expired":
    100 				world.missionExpiry[0].expiresAt = time.Now().Add(-time.Second)
    101 			case "completed":
    102 				world.missionExpiry[0].completed = true
    103 			case "full inventory":
    104 				for range 27 {
    105 					if granted, err := world.grantItem(player, 42640); err != nil || !granted {
    106 						t.Fatal(granted, err)
    107 					}
    108 				}
    109 			case "banked key", "reclaimed key":
    110 				inventory := player.inventory
    111 				key := inventory.Items[1]
    112 				inventory.Items = slices.Delete(slices.Clone(inventory.Items), 1, 2)
    113 				if scenario == "banked key" {
    114 					key.Slot = 0
    115 					inventory.Bank = []ownedItem{key}
    116 				} else {
    117 					inventory.Reclaim = []reclaimItem{{Item: key, AvailableAt: time.Now().Add(time.Minute)}}
    118 				}
    119 				if err := world.saveInventory(player, inventory); err != nil {
    120 					t.Fatal(err)
    121 				}
    122 			}
    123 			before, err := readTestItemStore(world)
    124 			if err != nil {
    125 				t.Fatal(err)
    126 			}
    127 			inventory, lastID := player.inventory, world.nextItem
    128 			auditCheckpointWrites(t, world)
    129 
    130 			err = world.handleItemCombination(world.clients[1], request)
    131 			after, readErr := readTestItemStore(world)
    132 
    133 			if err != nil || readErr != nil || !bytes.Equal(before, after) || len(checkpointWrites(t, world)) != 0 ||
    134 				!reflect.DeepEqual(player.inventory, inventory) || world.nextItem != lastID {
    135 				t.Fatal("refused copy changed ownership or allocation", err, readErr)
    136 			}
    137 			if scenario == "banked key" || scenario == "reclaimed key" {
    138 				if len(output.packets) != 0 {
    139 					t.Fatal("a non-carried key was treated as a current combination target")
    140 				}
    141 			} else if !reflect.DeepEqual(output.packets, [][]byte{targetPacket(characterActionPacket(1, [5]uint32{84, 2}))}) {
    142 				t.Fatal("unsupported key copying omitted ordinary combination failure")
    143 			}
    144 		})
    145 	}
    146 }
    147 
    148 func TestMissionKeyCopyRollsBackRequiredWritesAndRetries(t *testing.T) {
    149 	for _, scenario := range []struct{ name, sql string }{
    150 		{"item abort", "CREATE TRIGGER fail_copy BEFORE INSERT ON items WHEN NEW.id=4 BEGIN SELECT RAISE(ABORT,'copy'); END"},
    151 		{"item ignored", "CREATE TRIGGER fail_copy BEFORE INSERT ON items WHEN NEW.id=4 BEGIN SELECT RAISE(IGNORE); END"},
    152 		{"placement ignored", "CREATE TRIGGER fail_copy BEFORE INSERT ON item_locations WHEN NEW.item_id=4 BEGIN SELECT RAISE(IGNORE); END"},
    153 		{"binding abort", "CREATE TRIGGER fail_copy BEFORE INSERT ON mission_keys BEGIN SELECT RAISE(ABORT,'binding'); END"},
    154 		{"binding ignored", "CREATE TRIGGER fail_copy BEFORE INSERT ON mission_keys BEGIN SELECT RAISE(IGNORE); END"},
    155 		{"late binding deletion", "CREATE TRIGGER fail_copy AFTER UPDATE OF last_item_id ON world BEGIN DELETE FROM mission_keys WHERE item_id=4; END"},
    156 		{"late placement deletion", "CREATE TRIGGER fail_copy AFTER UPDATE OF last_item_id ON world BEGIN DELETE FROM item_locations WHERE item_id=4; END"},
    157 		{"commit", "CREATE TABLE pending_copy (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER fail_copy AFTER INSERT ON mission_keys BEGIN INSERT INTO pending_copy VALUES(999999); END"},
    158 	} {
    159 		t.Run(scenario.name, func(t *testing.T) {
    160 			world, output := newMissionKeyCopyWorld(t)
    161 			before := world.characters[1].inventory
    162 			if _, err := world.db.Exec(scenario.sql); err != nil {
    163 				t.Fatal(err)
    164 			}
    165 
    166 			failure := world.handleItemCombination(world.clients[1], combinationRequest(1, 66, 65))
    167 			cold := newTestInventoryServer(t)
    168 
    169 			var bindings int
    170 			if err := cold.db.QueryRow("SELECT count(*) FROM mission_keys").Scan(&bindings); err != nil {
    171 				t.Fatal(err)
    172 			}
    173 			if failure == nil || bindings != 1 || world.nextItem != 3 || cold.nextItem != 3 || len(output.packets) != 0 ||
    174 				!reflect.DeepEqual(world.characters[1].inventory, before) || !reflect.DeepEqual(cold.characters[1].inventory, before) {
    175 				t.Fatal("failed copy published or retained an unbound key, spent inputs or lost allocation", failure)
    176 			}
    177 
    178 			if _, err := world.db.Exec("DROP TRIGGER fail_copy"); err != nil {
    179 				t.Fatal(err)
    180 			}
    181 			if err := world.handleItemCombination(world.clients[1], combinationRequest(1, 66, 65)); err != nil {
    182 				t.Fatal(err)
    183 			}
    184 			cold = newTestInventoryServer(t)
    185 			var mission uint32
    186 			err := cold.db.QueryRow("SELECT mission_id FROM mission_keys WHERE item_id=5").Scan(&mission)
    187 
    188 			if err != nil || mission != 2 || cold.nextItem != 5 || len(output.packets) != 1 || len(cold.characters[1].inventory.Items) != 4 ||
    189 				!slices.Equal(cold.characters[1].inventory.Items[:3], before.Items) || cold.characters[1].inventory.Credits != 4 {
    190 				t.Fatal("copy retry lost an input or its exact bound result", err)
    191 			}
    192 		})
    193 	}
    194 }
    195 
    196 func TestMissionKeyCopyCanCopyACopyAndSerializeConcurrentCopies(t *testing.T) {
    197 	world, output := newMissionKeyCopyWorld(t)
    198 	client := world.clients[1]
    199 	if err := world.handleItemCombination(client, combinationRequest(1, 66, 65)); err != nil {
    200 		t.Fatal(err)
    201 	}
    202 	var pending sync.WaitGroup
    203 	failures := make(chan error, 2)
    204 	shutdown := startTestService(t, world)
    205 	owner, err := world.world.owner(1)
    206 	if err != nil {
    207 		t.Fatal(err)
    208 	}
    209 
    210 	for range 2 {
    211 		pending.Add(1)
    212 		go func() {
    213 			defer pending.Done()
    214 			failures <- owner.call(zonePacket{client, combinationRequest(1, 66, 67)})
    215 		}()
    216 	}
    217 	pending.Wait()
    218 	close(failures)
    219 	if err := shutdown(); err != nil {
    220 		t.Fatal(err)
    221 	}
    222 	cold := newTestInventoryServer(t)
    223 	var bindings int
    224 	err = cold.db.QueryRow("SELECT count(*) FROM mission_keys WHERE mission_id=2 AND item_id IN (2,4,5,6)").Scan(&bindings)
    225 
    226 	for failure := range failures {
    227 		if failure != nil {
    228 			t.Fatal(failure)
    229 		}
    230 	}
    231 	if err != nil || bindings != 4 || cold.nextItem != 6 || len(cold.characters[1].inventory.Items) != 6 || len(output.packets) != 3 ||
    232 		cold.characters[1].inventory.Items[2] != (ownedItem{ID: 3, Type: 51054, Template: 28564, Quality: 1, Slot: 66, Count: 1}) {
    233 		t.Fatal("copies of a copy lost reusable inputs, assignment or distinct atomic identities", err)
    234 	}
    235 }
    236 
    237 func TestMissionKeyCopyOutputFailureRetainsCommittedBinding(t *testing.T) {
    238 	world, output := newMissionKeyCopyWorld(t)
    239 	client := world.clients[1]
    240 	client.writeWake, client.writeClosed = make(chan struct{}, 1), true
    241 
    242 	failure := world.handleItemCombination(client, combinationRequest(1, 66, 65))
    243 	cold := newTestInventoryServer(t)
    244 	var mission uint32
    245 	err := cold.db.QueryRow("SELECT mission_id FROM mission_keys WHERE item_id=4").Scan(&mission)
    246 
    247 	if failure != net.ErrClosed || err != nil || mission != 2 || cold.nextItem != 4 || len(output.packets) != 0 || len(cold.characters[1].inventory.Items) != 4 {
    248 		t.Fatal("lost output rolled back a committed copy or lost its binding", failure, err)
    249 	}
    250 }
    251 
    252 func TestMissionKeyCopyTradedKeyCanBeCopiedAndAdmitItsNewHolder(t *testing.T) {
    253 	world, _ := newMissionKeyCopyWorld(t)
    254 	owner := world.characters[1]
    255 	data := owner.userData()
    256 	data.ID, data.Name = 2, "Key holder"
    257 	guest := data.character()
    258 	guest.geometry = world.geometry
    259 	world.characters[2] = guest
    260 	world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: &combatTestConn{}}
    261 	if err := world.saveUser(guest); err != nil {
    262 		t.Fatal(err)
    263 	}
    264 	if err := world.saveInventory(guest, playerInventory{}); err != nil {
    265 		t.Fatal(err)
    266 	}
    267 	if err := world.handleItemCombination(world.clients[1], combinationRequest(1, 66, 65)); err != nil {
    268 		t.Fatal(err)
    269 	}
    270 
    271 	playerTradeRequest(t, world, 1, 0, [2]uint32{50000, 2}, [2]uint32{})
    272 	playerTradeRequest(t, world, 1, 4, [2]uint32{50000, 1}, [2]uint32{104, 67})
    273 	playerTradeRequest(t, world, 1, 1, [2]uint32{}, [2]uint32{})
    274 	playerTradeRequest(t, world, 2, 1, [2]uint32{}, [2]uint32{})
    275 	if granted, err := world.grantItem(guest, 28564); err != nil || !granted {
    276 		t.Fatal(granted, err)
    277 	}
    278 	if err := world.handleItemCombination(world.clients[2], combinationRequest(2, 65, 64)); err != nil {
    279 		t.Fatal(err)
    280 	}
    281 	if err := world.handleInventory(world.clients[2], characterActionPacket(2, [5]uint32{112, 104, 64, 28577, 28577})[20:]); err != nil {
    282 		t.Fatal(err)
    283 	}
    284 	guest.position, guest.rotation = [3]float32{89.30216, 115.75, 152.5}, [4]float32{0, 1, 0, 0}
    285 	if err := world.handleMovement(world.clients[2], playerMovementRequest(guest, 1)); err != nil {
    286 		t.Fatal(err)
    287 	}
    288 	cold := reloadMissionEntranceWorld(t)
    289 	var mission uint32
    290 	err := cold.db.QueryRow("SELECT mission_id FROM mission_keys WHERE item_id=6").Scan(&mission)
    291 
    292 	if err != nil || mission != 2 || cold.characters[2].playfield != 65536 || len(cold.characters[2].missions) != 0 ||
    293 		!slices.Equal(cold.characters[2].inventory.Items, []ownedItem{
    294 			{ID: 5, Type: 51054, Template: 28564, Quality: 1, Slot: 65, Count: 1},
    295 			{ID: 6, Type: 51053, Template: 28577, Quality: 1, Slot: 66, Count: 1}}) ||
    296 		len(cold.characters[1].inventory.Items) != 3 || cold.characters[1].inventory.Credits != 4 {
    297 		t.Fatal("trade or guest copying lost the source assignment or required journal ownership", err)
    298 	}
    299 }