From 6da2d9b89c6eb54058287bd0bbdc2bcba7bb3570 Mon Sep 17 00:00:00 2001
From: Flechazo <2558755403@qq.com>
Date: Mon, 19 Oct 2026 00:04:02 +0800
Subject: [PATCH] feat(all): add server gameplay systems, one-step launcher
installation, clearer update logs and shared file utilities
Server:
- Add castle and total war battles, IB battles, roguelike runs with castle and roguelike rankings, cafeteria and dating, life content, spine interactions and recordings, popularity rankings, gacha history and selection draws, map exploration, quest previews and completion, passes, rhythm events, quick battles, achievement progress, resource items, prestige illustrations and community notices.
- Report structured request errors from the gateway, validate avatars, and extend settlement evidence and existing domain handlers.
- Let bd2-host.sh deploy from a source directory or a prebuilt image and update the deployment docs and Docker ignore list.
Launcher:
- Prepare a new installation directly from the launcher (download, BepInEx, catalog, patch, plugins) through a shared preparation package also used by bd2client prepare.
- Launching and preparing now wait for a running background update instead of failing with "Another update operation is in progress"; manual update checks wait as well, and launch downloads no longer use the 12-second resource-policy timeout.
- Log what each update check found, every downloaded file, the server requirement, the game resource decision and installed plugins; skip warnings caused by closing the launcher.
Shared:
- Move file hashing and atomic replacement into common/util and use it from the build, release, launcher and server code.
---
Dockerfile.server.dockerignore | 2 +
README.md | 13 +-
go/build/client_instance.go | 9 +-
go/build/release_pipeline.go | 3 +-
go/build/release_publish.go | 3 +-
go/build/release_schedules.go | 3 +-
go/cmd/bd2client/main.go | 8 +
go/cmd/bd2client/prepare.go | 134 +--
go/internal/client/app/app.go | 80 +-
go/internal/client/app/platform_darwin.go | 3 +-
go/internal/client/app/platform_other.go | 3 +-
go/internal/client/app/platform_windows.go | 33 +-
go/internal/client/app/prepare.go | 78 ++
go/internal/client/app/web/index.html | 18 +-
go/internal/client/app/web/lang/en_us.json | 19 +-
go/internal/client/app/web/lang/ja_jp.json | 19 +-
go/internal/client/app/web/lang/ko_kr.json | 19 +-
go/internal/client/app/web/lang/zh_cn.json | 19 +-
go/internal/client/app/web/lang/zh_tw.json | 19 +-
go/internal/client/config/config.go | 4 +
go/internal/client/config/preferences.go | 3 +
go/internal/client/download/archive.go | 32 +-
go/internal/client/download/client.go | 33 +-
go/internal/client/download/client_test.go | 161 +++-
go/internal/client/download/game_receipt.go | 186 ++++
go/internal/client/download/resources.go | 81 +-
go/internal/client/download/transfer.go | 99 ++-
go/internal/client/plugin/build_cache.go | 25 +-
go/internal/client/plugin/build_test.go | 3 +-
go/internal/client/plugin/install.go | 8 +-
go/internal/client/preparation/prepare.go | 250 ++++++
go/internal/client/setup/catalog_cache.go | 107 +++
go/internal/client/setup/local_catalog.go | 207 ++++-
.../client/setup/local_catalog_test.go | 251 ++++++
go/internal/client/setup/settings_test.go | 40 +
go/internal/client/setup/setup.go | 42 +-
go/internal/client/update/game.go | 22 +-
go/internal/client/update/manager.go | 108 ++-
go/internal/client/update/selfupdate.go | 5 +-
go/internal/client/update/selfupdate_test.go | 5 +-
go/internal/common/config/config.go | 5 +-
go/internal/common/release/fetch.go | 20 +-
go/internal/common/util/file.go | 21 +
go/internal/common/util/random.go | 42 +
.../common/{config => util}/replace_other.go | 2 +-
.../{config => util}/replace_windows.go | 2 +-
go/internal/common/util/well512.go | 31 +
go/internal/server/admin/console.go | 7 +-
.../server/admin/spine_recording_test.go | 54 ++
go/internal/server/admin/store.go | 15 +-
.../server/admin/web/assets/lang/en_us.json | 6 +-
.../server/admin/web/assets/lang/ja_jp.json | 6 +-
.../server/admin/web/assets/lang/ko_kr.json | 6 +-
.../server/admin/web/assets/lang/zh_cn.json | 6 +-
.../server/admin/web/assets/lang/zh_tw.json | 6 +-
.../app/castle_battle_integration_test.go | 163 ++++
go/internal/server/app/design.go | 50 ++
.../event_mission_update_integration_test.go | 89 ++
.../friendship_lifecycle_integration_test.go | 259 ++++++
.../server/app/guide_pass_integration_test.go | 99 +++
.../app/ib_lifecycle_integration_test.go | 133 +++
.../app/map_exploration_integration_test.go | 89 ++
..._hunt_reward_lifecycle_integration_test.go | 129 +++
.../app/player_achievement_projection.go | 9 +
go/internal/server/app/player_assets.go | 1 +
.../server/app/player_castle_ranking.go | 78 ++
go/internal/server/app/player_events.go | 28 +-
go/internal/server/app/player_executor.go | 24 +-
go/internal/server/app/player_factory.go | 24 +-
go/internal/server/app/player_gameplay.go | 3 +
go/internal/server/app/player_ib.go | 47 ++
go/internal/server/app/player_interaction.go | 37 +
.../server/app/player_optional_gameplay.go | 133 +++
go/internal/server/app/player_roguelike.go | 172 ++++
go/internal/server/app/player_session.go | 13 +
go/internal/server/app/player_system.go | 7 +
go/internal/server/app/player_text.go | 39 +-
go/internal/server/app/player_world_roster.go | 5 +-
.../prestige_illustration_integration_test.go | 126 +++
.../app/quest_battle_integration_test.go | 46 +-
go/internal/server/app/realtime_tickets.go | 8 +-
.../app/resource_item_integration_test.go | 62 ++
.../app/reward_state_integration_test.go | 370 ++++++++
.../server/app/roguelike_integration_test.go | 226 +++++
go/internal/server/app/serve.go | 9 +-
go/internal/server/app/shared_popularity.go | 484 +++++++++++
.../server/app/shared_popularity_test.go | 338 ++++++++
go/internal/server/app/shared_pvp.go | 128 +++
.../server/app/shared_recommendation.go | 11 +
go/internal/server/app/shared_runtime.go | 28 +-
go/internal/server/app/spine_recordings.go | 101 +++
.../app/spine_recordings_integration_test.go | 177 ++++
.../app/story_archive_integration_test.go | 102 +++
.../app/story_checkpoint_integration_test.go | 21 +
.../app/talent_travel_integration_test.go | 167 ++++
.../server/design/gameconfig/config.go | 3 +
.../server/design/gameconfig/schema.go | 4 +
.../design/gameconfig/spine_recording.go | 29 +
.../design/gamedata/cafeteria_dating.go | 155 ++++
.../server/design/gamedata/castle_rewards.go | 372 ++++++++
.../design/gamedata/collection_statistics.go | 126 +++
.../design/gamedata/community_rewards.go | 33 +
.../server/design/gamedata/equipment_craft.go | 5 +-
.../server/design/gamedata/equipment_gacha.go | 16 +-
.../gamedata/equipment_option_reroll.go | 5 +-
.../server/design/gamedata/event_ap.go | 2 +-
.../server/design/gamedata/event_battle.go | 102 +++
.../server/design/gamedata/event_play.go | 1 +
.../server/design/gamedata/field_objects.go | 3 +-
.../server/design/gamedata/field_pack.go | 2 +-
.../server/design/gamedata/first_gacha.go | 3 +-
go/internal/server/design/gamedata/gacha.go | 54 +-
go/internal/server/design/gamedata/ib.go | 189 +++++
go/internal/server/design/gamedata/life.go | 144 ++++
.../server/design/gamedata/quest_titles.go | 44 +
.../server/design/gamedata/resource_items.go | 89 ++
.../server/design/gamedata/reward_graph.go | 9 +-
.../server/design/gamedata/reward_skin.go | 34 +-
.../server/design/gamedata/roguelike.go | 265 ++++++
.../design/gamedata/roguelike_battle.go | 102 +++
go/internal/server/design/gamedata/source.go | 4 +
.../design/gamedata/spine_interaction.go | 118 +++
.../server/design/gamedata/total_war_enemy.go | 59 ++
.../design/gamedata/total_war_presets.go | 29 +
.../server/domain/battle/castle/battle.go | 266 ++++++
.../domain/battle/castle/progress_test.go | 252 ++++++
.../server/domain/battle/castle/ranking.go | 271 ++++++
.../server/domain/battle/castle/service.go | 467 +++++++++++
.../server/domain/battle/castle/totalwar.go | 212 +++++
.../domain/battle/castle/totalwar_deck.go | 497 +++++++++++
.../battle/castle/totalwar_deck_test.go | 793 ++++++++++++++++++
.../domain/battle/hunting/protocol_adapter.go | 19 +-
.../server/domain/battle/ib/service.go | 729 ++++++++++++++++
.../server/domain/battle/ib/service_test.go | 413 +++++++++
.../battle/monsterhunt/protocol_adapter.go | 43 +-
.../domain/battle/monsterhunt/rewards.go | 24 +-
.../server/domain/battle/protocol_adapter.go | 9 +
.../server/domain/battle/pvp/contracts.go | 5 +
.../domain/battle/pvp/protocol_adapter.go | 4 +
.../server/domain/battle/pvp/service.go | 13 +
.../server/domain/battle/roguelike/battle.go | 288 +++++++
.../domain/battle/roguelike/branches_test.go | 290 +++++++
.../domain/battle/roguelike/costume_offers.go | 52 ++
.../battle/roguelike/costume_offers_test.go | 186 ++++
.../server/domain/battle/roguelike/events.go | 202 +++++
.../domain/battle/roguelike/lifecycle_test.go | 266 ++++++
.../domain/battle/roguelike/progression.go | 281 +++++++
.../domain/battle/roguelike/protocol.go | 83 ++
.../domain/battle/roguelike/relic_effects.go | 26 +
.../server/domain/battle/roguelike/run.go | 490 +++++++++++
.../server/domain/battle/roguelike/service.go | 321 +++++++
.../domain/battle/roguelike/shop_roster.go | 330 ++++++++
go/internal/server/domain/battle/session.go | 2 +-
.../domain/battle/settlement_evidence.go | 17 +
.../server/domain/cafeteria/service.go | 507 +++++++++++
.../server/domain/cafeteria/service_test.go | 223 +++++
.../server/domain/command/request_error.go | 16 +
.../server/domain/commerce/gacha/gacha.go | 1 +
.../server/domain/commerce/gacha/history.go | 257 ++++++
.../history_equipment_integration_test.go | 155 ++++
.../domain/commerce/gacha/history_test.go | 220 +++++
.../gacha/overflow_draw_integration_test.go | 145 ++++
.../domain/commerce/gacha/protocol_adapter.go | 91 +-
.../gacha/selection_integration_test.go | 50 ++
.../domain/commerce/gacha/selection_test.go | 184 ++++
.../server/domain/commerce/npcshop/shop.go | 16 +-
go/internal/server/domain/dating/service.go | 369 ++++++++
.../server/domain/dating/service_test.go | 328 ++++++++
.../domain/events/actions/friendship.go | 80 ++
.../domain/events/actions/protocol_adapter.go | 44 +-
.../server/domain/events/actions/square.go | 9 +-
.../server/domain/events/ap_refresh.go | 35 +-
go/internal/server/domain/events/boxes.go | 11 +-
go/internal/server/domain/events/dating_ap.go | 74 ++
go/internal/server/domain/events/economy.go | 8 +-
.../server/domain/events/exchange/service.go | 9 +-
.../server/domain/events/games/games.go | 9 +-
.../server/domain/events/life_economy.go | 15 +
.../events/play/achievement_progress.go | 258 ++++++
.../events/play/achievement_progress_test.go | 112 +++
.../server/domain/events/play/field_run.go | 7 +-
go/internal/server/domain/events/play/play.go | 9 +
.../server/domain/events/play/progress.go | 9 +-
.../domain/events/play/protocol_adapter.go | 16 +
.../server/domain/events/play/quick_battle.go | 156 ++++
.../domain/events/play/quick_battle_test.go | 117 +++
.../server/domain/events/play/routes.go | 1 +
.../domain/events/play/single_player.go | 45 +-
.../domain/events/play/single_player_test.go | 34 +-
.../server/domain/events/play/survival.go | 29 +-
.../server/domain/events/protocol_adapter.go | 36 +-
go/internal/server/domain/events/registry.go | 5 +
.../server/domain/events/resource_items.go | 88 ++
.../domain/events/resource_items_test.go | 180 ++++
.../server/domain/events/roguelike_ap_test.go | 76 ++
.../server/domain/events/tasks/passes.go | 49 ++
.../domain/events/tasks/protocol_adapter.go | 26 +-
.../server/domain/events/tasks/rhythm.go | 86 ++
.../server/domain/events/tasks/service.go | 5 +-
go/internal/server/domain/fishing/fishing.go | 9 +-
go/internal/server/domain/identity/service.go | 34 +-
go/internal/server/domain/inventory/owned.go | 25 +-
.../server/domain/inventory/preset_runtime.go | 5 +
.../inventory/prestige_illustrations.go | 31 +
.../inventory/protocol_items_adapter.go | 1 +
go/internal/server/domain/life/bonuses.go | 90 ++
go/internal/server/domain/life/economy.go | 257 ++++++
.../domain/life/gameplay_integration_test.go | 254 ++++++
go/internal/server/domain/life/helpers.go | 388 +++++++++
go/internal/server/domain/life/life.go | 506 +++++++++++
go/internal/server/domain/life/life_test.go | 300 +++++++
go/internal/server/domain/life/world.go | 600 +++++++++++++
go/internal/server/domain/notice/board.go | 4 +-
go/internal/server/domain/notice/community.go | 107 +++
.../server/domain/notice/protocol_adapter.go | 3 +
.../domain/profile/avatar_validation.go | 29 +
go/internal/server/domain/ranking/castle.go | 173 ++++
.../server/domain/ranking/castle_test.go | 201 +++++
.../server/domain/ranking/popularity.go | 16 +
.../server/domain/ranking/roguelike.go | 190 +++++
.../server/domain/ranking/roguelike_test.go | 84 ++
.../server/domain/roster/collection.go | 14 +-
.../domain/roster/collection_entries.go | 1 +
go/internal/server/domain/roster/deck/deck.go | 1 +
.../domain/roster/deck/protocol_adapter.go | 14 +-
.../domain/roster/deck/recommendation.go | 27 +
.../server/domain/roster/deck/waypoint.go | 4 +
.../server/domain/roster/friendship.go | 28 +-
.../server/domain/roster/gacha_history.go | 150 ++++
go/internal/server/domain/roster/growth.go | 5 +-
.../domain/roster/protocol_costume_adapter.go | 63 +-
.../domain/roster/protocol_talent_adapter.go | 30 +-
go/internal/server/domain/roster/recruit.go | 6 +-
.../server/domain/roster/spine_interaction.go | 257 ++++++
.../server/domain/roster/spine_recordings.go | 450 ++++++++++
.../server/domain/roster/talent_dispatch.go | 9 +-
.../server/domain/roster/talent_use.go | 55 +-
.../domain/world/field_object_routes.go | 24 +-
.../field_reward_claim_integration_test.go | 91 ++
.../server/domain/world/map_exploration.go | 94 +++
.../server/domain/world/npc_reputation.go | 49 +-
...pc_reputation_download_integration_test.go | 107 +++
.../server/domain/world/pack_purchase.go | 1 +
.../domain/world/progress/map_exploration.go | 59 ++
.../domain/world/protocol_field_adapter.go | 6 -
.../domain/world/protocol_story_adapter.go | 70 +-
.../server/domain/world/quest_completion.go | 68 ++
.../server/domain/world/quest_preview.go | 64 ++
.../domain/world/side_quest_chain_test.go | 18 +-
.../server/domain/world/talent_effects.go | 22 +
.../server/gateway/session/request_error.go | 115 +++
.../gateway/session/request_error_test.go | 58 ++
go/internal/server/gateway/session/server.go | 22 +-
go/internal/server/gateway/transport/http.go | 4 +
.../server/platform/updates/schedules.go | 5 +-
go/internal/server/platform/updates/switch.go | 3 +-
.../server/protocol/defaults/bootstrap.go | 16 -
.../server/protocol/defaults/feature.go | 42 +-
.../server/protocol/defaults/standalone.go | 27 -
go/internal/server/protocol/login/login.go | 9 +
.../server/protocol/login/protocol_adapter.go | 13 +
.../server/runtime/delivery/dispatcher.go | 9 +-
go/internal/server/runtime/player/runtime.go | 3 +-
go/internal/server/runtime/room/manager.go | 9 +-
tools/server/bd2-host.sh | 111 ++-
265 files changed, 23870 insertions(+), 1143 deletions(-)
create mode 100644 go/internal/client/app/prepare.go
create mode 100644 go/internal/client/download/game_receipt.go
create mode 100644 go/internal/client/preparation/prepare.go
create mode 100644 go/internal/client/setup/catalog_cache.go
create mode 100644 go/internal/client/setup/settings_test.go
create mode 100644 go/internal/common/util/file.go
create mode 100644 go/internal/common/util/random.go
rename go/internal/common/{config => util}/replace_other.go (93%)
rename go/internal/common/{config => util}/replace_windows.go (98%)
create mode 100644 go/internal/common/util/well512.go
create mode 100644 go/internal/server/admin/spine_recording_test.go
create mode 100644 go/internal/server/app/castle_battle_integration_test.go
create mode 100644 go/internal/server/app/event_mission_update_integration_test.go
create mode 100644 go/internal/server/app/friendship_lifecycle_integration_test.go
create mode 100644 go/internal/server/app/guide_pass_integration_test.go
create mode 100644 go/internal/server/app/ib_lifecycle_integration_test.go
create mode 100644 go/internal/server/app/monster_hunt_reward_lifecycle_integration_test.go
create mode 100644 go/internal/server/app/player_castle_ranking.go
create mode 100644 go/internal/server/app/player_ib.go
create mode 100644 go/internal/server/app/player_interaction.go
create mode 100644 go/internal/server/app/player_optional_gameplay.go
create mode 100644 go/internal/server/app/player_roguelike.go
create mode 100644 go/internal/server/app/prestige_illustration_integration_test.go
create mode 100644 go/internal/server/app/resource_item_integration_test.go
create mode 100644 go/internal/server/app/reward_state_integration_test.go
create mode 100644 go/internal/server/app/roguelike_integration_test.go
create mode 100644 go/internal/server/app/shared_popularity.go
create mode 100644 go/internal/server/app/shared_popularity_test.go
create mode 100644 go/internal/server/app/spine_recordings.go
create mode 100644 go/internal/server/app/spine_recordings_integration_test.go
create mode 100644 go/internal/server/app/story_archive_integration_test.go
create mode 100644 go/internal/server/app/talent_travel_integration_test.go
create mode 100644 go/internal/server/design/gameconfig/spine_recording.go
create mode 100644 go/internal/server/design/gamedata/cafeteria_dating.go
create mode 100644 go/internal/server/design/gamedata/castle_rewards.go
create mode 100644 go/internal/server/design/gamedata/collection_statistics.go
create mode 100644 go/internal/server/design/gamedata/community_rewards.go
create mode 100644 go/internal/server/design/gamedata/event_battle.go
create mode 100644 go/internal/server/design/gamedata/ib.go
create mode 100644 go/internal/server/design/gamedata/life.go
create mode 100644 go/internal/server/design/gamedata/quest_titles.go
create mode 100644 go/internal/server/design/gamedata/resource_items.go
create mode 100644 go/internal/server/design/gamedata/roguelike.go
create mode 100644 go/internal/server/design/gamedata/roguelike_battle.go
create mode 100644 go/internal/server/design/gamedata/spine_interaction.go
create mode 100644 go/internal/server/design/gamedata/total_war_enemy.go
create mode 100644 go/internal/server/design/gamedata/total_war_presets.go
create mode 100644 go/internal/server/domain/battle/castle/battle.go
create mode 100644 go/internal/server/domain/battle/castle/progress_test.go
create mode 100644 go/internal/server/domain/battle/castle/ranking.go
create mode 100644 go/internal/server/domain/battle/castle/service.go
create mode 100644 go/internal/server/domain/battle/castle/totalwar.go
create mode 100644 go/internal/server/domain/battle/castle/totalwar_deck.go
create mode 100644 go/internal/server/domain/battle/castle/totalwar_deck_test.go
create mode 100644 go/internal/server/domain/battle/ib/service.go
create mode 100644 go/internal/server/domain/battle/ib/service_test.go
create mode 100644 go/internal/server/domain/battle/roguelike/battle.go
create mode 100644 go/internal/server/domain/battle/roguelike/branches_test.go
create mode 100644 go/internal/server/domain/battle/roguelike/costume_offers.go
create mode 100644 go/internal/server/domain/battle/roguelike/costume_offers_test.go
create mode 100644 go/internal/server/domain/battle/roguelike/events.go
create mode 100644 go/internal/server/domain/battle/roguelike/lifecycle_test.go
create mode 100644 go/internal/server/domain/battle/roguelike/progression.go
create mode 100644 go/internal/server/domain/battle/roguelike/protocol.go
create mode 100644 go/internal/server/domain/battle/roguelike/relic_effects.go
create mode 100644 go/internal/server/domain/battle/roguelike/run.go
create mode 100644 go/internal/server/domain/battle/roguelike/service.go
create mode 100644 go/internal/server/domain/battle/roguelike/shop_roster.go
create mode 100644 go/internal/server/domain/battle/settlement_evidence.go
create mode 100644 go/internal/server/domain/cafeteria/service.go
create mode 100644 go/internal/server/domain/cafeteria/service_test.go
create mode 100644 go/internal/server/domain/command/request_error.go
create mode 100644 go/internal/server/domain/commerce/gacha/history.go
create mode 100644 go/internal/server/domain/commerce/gacha/history_equipment_integration_test.go
create mode 100644 go/internal/server/domain/commerce/gacha/history_test.go
create mode 100644 go/internal/server/domain/commerce/gacha/overflow_draw_integration_test.go
create mode 100644 go/internal/server/domain/commerce/gacha/selection_integration_test.go
create mode 100644 go/internal/server/domain/commerce/gacha/selection_test.go
create mode 100644 go/internal/server/domain/dating/service.go
create mode 100644 go/internal/server/domain/dating/service_test.go
create mode 100644 go/internal/server/domain/events/actions/friendship.go
create mode 100644 go/internal/server/domain/events/dating_ap.go
create mode 100644 go/internal/server/domain/events/life_economy.go
create mode 100644 go/internal/server/domain/events/play/achievement_progress.go
create mode 100644 go/internal/server/domain/events/play/achievement_progress_test.go
create mode 100644 go/internal/server/domain/events/play/quick_battle.go
create mode 100644 go/internal/server/domain/events/play/quick_battle_test.go
create mode 100644 go/internal/server/domain/events/resource_items.go
create mode 100644 go/internal/server/domain/events/resource_items_test.go
create mode 100644 go/internal/server/domain/events/roguelike_ap_test.go
create mode 100644 go/internal/server/domain/events/tasks/passes.go
create mode 100644 go/internal/server/domain/events/tasks/rhythm.go
create mode 100644 go/internal/server/domain/inventory/prestige_illustrations.go
create mode 100644 go/internal/server/domain/life/bonuses.go
create mode 100644 go/internal/server/domain/life/economy.go
create mode 100644 go/internal/server/domain/life/gameplay_integration_test.go
create mode 100644 go/internal/server/domain/life/helpers.go
create mode 100644 go/internal/server/domain/life/life.go
create mode 100644 go/internal/server/domain/life/life_test.go
create mode 100644 go/internal/server/domain/life/world.go
create mode 100644 go/internal/server/domain/notice/community.go
create mode 100644 go/internal/server/domain/profile/avatar_validation.go
create mode 100644 go/internal/server/domain/ranking/castle.go
create mode 100644 go/internal/server/domain/ranking/castle_test.go
create mode 100644 go/internal/server/domain/ranking/popularity.go
create mode 100644 go/internal/server/domain/ranking/roguelike.go
create mode 100644 go/internal/server/domain/ranking/roguelike_test.go
create mode 100644 go/internal/server/domain/roster/gacha_history.go
create mode 100644 go/internal/server/domain/roster/spine_interaction.go
create mode 100644 go/internal/server/domain/roster/spine_recordings.go
create mode 100644 go/internal/server/domain/world/field_reward_claim_integration_test.go
create mode 100644 go/internal/server/domain/world/map_exploration.go
create mode 100644 go/internal/server/domain/world/npc_reputation_download_integration_test.go
create mode 100644 go/internal/server/domain/world/progress/map_exploration.go
create mode 100644 go/internal/server/domain/world/quest_completion.go
create mode 100644 go/internal/server/domain/world/quest_preview.go
create mode 100644 go/internal/server/gateway/session/request_error.go
create mode 100644 go/internal/server/gateway/session/request_error_test.go
delete mode 100644 go/internal/server/protocol/defaults/bootstrap.go
delete mode 100644 go/internal/server/protocol/defaults/standalone.go
diff --git a/Dockerfile.server.dockerignore b/Dockerfile.server.dockerignore
index 0528ee4..427fea9 100644
--- a/Dockerfile.server.dockerignore
+++ b/Dockerfile.server.dockerignore
@@ -1,6 +1,8 @@
*
!go/
!go/**
+go/.cache/
+go/config.json
!versions.json
!CHANGELOG.md*
!UPDATE_FINGERPRINT.json
diff --git a/README.md b/README.md
index f8edb3b..f4bc73d 100644
--- a/README.md
+++ b/README.md
@@ -84,21 +84,24 @@ BD2 Launcher 是使用 Wails 的独立桌面游戏启动器。Windows 使用系
### 在 Linux 服务器上用 Docker 部署
-[`tools/server/bd2-host.sh`](tools/server/bd2-host.sh) 负责 Docker 主机上的全部工作:准备目录、生成认证主密钥、检出源码、安装更新交接单元,并从已发布的提交构建镜像、切换容器、等待就绪。需要 Docker(含 Compose 插件)、git、jq、curl、flock、nsenter 和 openssl,以 root 运行。一键安装并部署 `main` 的最新提交:
+[`tools/server/bd2-host.sh`](tools/server/bd2-host.sh) 负责 Docker 主机上的目录与密钥初始化、更新交接单元安装、镜像构建、容器切换和就绪检查。手动部署直接使用指定目录的当前源码(包括未提交的改动),或指定的 Docker 镜像,与 Git 提交、推送无关。需要 Docker(含 Compose 插件)、jq、curl、flock、nsenter、realpath 和 openssl,以 root 运行。从源码目录安装并部署:
```bash
-curl -fsSL https://raw.githubusercontent.com/Flechazo098/bd2/main/tools/server/bd2-host.sh -o bd2-host.sh && sudo sh bd2-host.sh setup
+sudo sh tools/server/bd2-host.sh setup "$PWD"
```
脚本安装到 `/opt/bd2/bd2-host.sh`,数据在 `/opt/bd2/data`,Compose 文件首次从 [模板](tools/server/compose.yaml) 生成为 `/opt/bd2/compose.yaml`(默认只在本机 `8080` 端口提供服务,请放在 HTTPS 反向代理之后)。之后:
```bash
-sudo /opt/bd2/bd2-host.sh deploy # 部署 main 的最新提交,或指定完整提交号
+sudo /opt/bd2/bd2-host.sh deploy /path/to/bd2 # 构建该目录当前源码
+sudo /opt/bd2/bd2-host.sh deploy --image bd2server:my-build
sudo /opt/bd2/bd2-host.sh status
-sudo /opt/bd2/bd2-host.sh rollback # 换回上次切换前的镜像;存档不回滚
+sudo /opt/bd2/bd2-host.sh rollback # 换回上次切换前的镜像;存档不会回滚
```
-在管理台应用的服务端更新也由同一脚本完成交接。路径、源码地址和 Compose 文件可在 `/etc/bd2/host.conf` 中以 `BD2_DIR=`、`SOURCE_URL=`、`COMPOSE_FILE=`、`SERVICE=`、`READY_PORT=`、`SEED_CONFIG_DIR=` 修改。不用 Docker 时,可使用 [systemd 单元模板](tools/server/bd2server.service)。
+省略源码路径时,`deploy` 使用 `/opt/bd2/source` 中已有的源码。指定镜像时,优先使用本机镜像,不存在则拉取,并以解析出的不可变镜像 ID 切换。首次安装若没有相邻的 Compose 模板和本地源码,脚本会用 Git 从 `SOURCE_URL` 获取初始源码。
+
+在管理台应用的服务端更新也由同一脚本完成交接,继续使用经过验证的发布请求;发布提供固定摘要的镜像时无需 Git,按源码更新时才获取对应提交。路径、源码地址和 Compose 文件可在 `/etc/bd2/host.conf` 中以 `BD2_DIR=`、`SOURCE_URL=`、`COMPOSE_FILE=`、`SERVICE=`、`READY_PORT=`、`SEED_CONFIG_DIR=` 修改。不用 Docker 时,可使用 [systemd 单元模板](tools/server/bd2server.service)。
服务端日志默认输出 INFO 及以上级别,仅终端启用颜色:TRACE 灰、DEBUG 青、INFO 绿、WARN 黄、ERROR 红。可用 `serve --log-level debug --log-color auto` 调整。级别支持 `trace/debug/info/warn/error`,颜色支持 `auto/always/never`。`auto` 下文件和重定向保持纯文本,`NO_COLOR` 或 `TERM=dumb` 也会关闭颜色;如需在 Docker 日志流中显示颜色,可显式选择 `always`。
diff --git a/go/build/client_instance.go b/go/build/client_instance.go
index 9194d29..becbdba 100644
--- a/go/build/client_instance.go
+++ b/go/build/client_instance.go
@@ -63,9 +63,14 @@ func (t task) runClient2(args []string) error {
return fmt.Errorf("load second client's connection settings: %w", err)
}
}
- if _, err := clientsetup.SaveSettings(instance.GameDirectory, settings, versions); err != nil {
+ if _, err := clientsetup.SaveSettings(instance.GameDirectory, settings); err != nil {
return fmt.Errorf("prepare second client's resources: %w", err)
}
+ if settings.CDNMode == clientconfig.CDNLocal {
+ if err := clientsetup.InstallLocalCatalog(instance.GameDirectory, settings.LocalResourceDirectory, versions.BundleVersion); err != nil {
+ return fmt.Errorf("prepare second client's catalog: %w", err)
+ }
+ }
return nil
}},
taskgraph.Task{Name: "instance:plugins", DependsOn: []string{"instance:prepare"}, Run: func(ctx context.Context) error {
@@ -78,7 +83,7 @@ func (t task) runClient2(args []string) error {
plugins := func(name string) string {
return filepath.Join(t.root, "plugins", name, "bin", "Release", "netstandard2.1", "BD2"+name+".dll")
}
- _, err := clientsetup.InstallPlugins(instance.GameDirectory, settings, versions, plugins("LocalIdentity"), plugins("LoginUI"), plugins("CashShop"), plugins("FChat"))
+ _, err := clientsetup.InstallPlugins(instance.GameDirectory, plugins("LocalIdentity"), plugins("LoginUI"), plugins("CashShop"), plugins("FChat"))
return err
}},
taskgraph.Task{Name: "instance:launcher", DependsOn: []string{"instance:plugins"}, Run: func(context.Context) error {
diff --git a/go/build/release_pipeline.go b/go/build/release_pipeline.go
index 63e3705..ac82c60 100644
--- a/go/build/release_pipeline.go
+++ b/go/build/release_pipeline.go
@@ -1,6 +1,7 @@
package main
import (
+ "bd2server/internal/common/util"
"bytes"
"context"
"encoding/json"
@@ -240,7 +241,7 @@ func (r *release) writePluginStore() error {
byID := versions.Plugins.ByID()
store := clientupdate.Store{Version: versions.ClientVersion}
for _, spec := range clientplugin.Shipped {
- sum, err := releasepkg.HashFile(filepath.Join(r.client, "plugins", spec.FileName()))
+ sum, err := util.SHA256File(filepath.Join(r.client, "plugins", spec.FileName()))
if err != nil {
return err
}
diff --git a/go/build/release_publish.go b/go/build/release_publish.go
index 540d045..0a9712e 100644
--- a/go/build/release_publish.go
+++ b/go/build/release_publish.go
@@ -2,6 +2,7 @@ package main
import (
"archive/zip"
+ "bd2server/internal/common/util"
"bytes"
"encoding/json"
"errors"
@@ -279,7 +280,7 @@ func (t task) releasePublish(args []string) error {
return err
}
publish := func(source, name, platform, id, version string) (releasepkg.File, error) {
- sum, err := releasepkg.HashFile(source)
+ sum, err := util.SHA256File(source)
if err != nil {
return releasepkg.File{}, err
}
diff --git a/go/build/release_schedules.go b/go/build/release_schedules.go
index 96ac667..74ef8d0 100644
--- a/go/build/release_schedules.go
+++ b/go/build/release_schedules.go
@@ -1,6 +1,7 @@
package main
import (
+ "bd2server/internal/common/util"
"encoding/json"
"fmt"
"os"
@@ -83,7 +84,7 @@ func (t task) stageSchedules(output string, versions versionconfig.Config) (*rel
}
for _, entry := range entries {
file := filepath.Join(source, entry.Name())
- sum, err := releasepkg.HashFile(file)
+ sum, err := util.SHA256File(file)
if err != nil {
return nil, err
}
diff --git a/go/cmd/bd2client/main.go b/go/cmd/bd2client/main.go
index d79a3fa..1a0fcab 100644
--- a/go/cmd/bd2client/main.go
+++ b/go/cmd/bd2client/main.go
@@ -7,6 +7,7 @@ import (
"fmt"
"os"
"os/signal"
+ "path/filepath"
clientapp "bd2server/internal/client/app"
clientconfig "bd2server/internal/client/config"
@@ -110,12 +111,19 @@ func runClient(args []string, options clientRunOptions) error {
*gameDir = preferences.GameDirectory
}
}
+ var packageDirectory, downloadManifest string
+ if options.versionConfigPath != "" {
+ packageDirectory = filepath.Dir(options.versionConfigPath)
+ downloadManifest = filepath.Join(packageDirectory, "tools", "client", "client-download.json")
+ }
if err := clientapp.Run(clientapp.Options{
InitialGameDir: *gameDir,
Logger: logger,
LogPath: logPath,
Versions: versions,
Development: options.versionConfigPath != "",
+ PackageDirectory: packageDirectory,
+ DownloadManifest: downloadManifest,
LocalIdentityPlugin: options.localIdentityPlugin,
LoginUIPlugin: options.loginUIPlugin,
CashShopPlugin: options.cashShopPlugin,
diff --git a/go/cmd/bd2client/prepare.go b/go/cmd/bd2client/prepare.go
index 83d3672..5aa600e 100644
--- a/go/cmd/bd2client/prepare.go
+++ b/go/cmd/bd2client/prepare.go
@@ -7,16 +7,10 @@ import (
"fmt"
"os"
"os/signal"
- "path/filepath"
"strings"
- "time"
clientconfig "bd2server/internal/client/config"
- "bd2server/internal/client/download"
- clientsetup "bd2server/internal/client/setup"
- commonconfig "bd2server/internal/common/config"
- "bd2server/internal/common/taskgraph"
- "bd2server/internal/common/versionconfig"
+ "bd2server/internal/client/preparation"
)
func prepareClient(args []string) error {
@@ -41,126 +35,22 @@ func prepareClient(args []string) error {
if fs.NArg() != 0 || *workers < 1 || *workers > 16 {
return errors.New("prepare accepts named options and workers must be 1-16")
}
- if *downloadOnly && *baseOnly {
- return errors.New("--download and --base select separate stages; omit both to run all stages")
- }
- if *baseOnly && *probeOnly {
- return errors.New("--probe-only cannot be used with --base")
- }
- if *packageDir == "" {
- executable, err := os.Executable()
- if err != nil {
- return err
- }
- *packageDir = filepath.Dir(executable)
- }
- var err error
- *packageDir, err = filepath.Abs(*packageDir)
- if err != nil {
- return err
- }
- if *versionPath == "" {
- *versionPath = filepath.Join(*packageDir, versionconfig.FileName)
- }
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
- var versions, downloaded versionconfig.Config
- var settings clientconfig.Settings
- graph, err := taskgraph.New(
- taskgraph.Task{Name: "download", Run: func(ctx context.Context) error {
- installed, err := download.Client(ctx, download.Options{
- PackageDir: *packageDir, Manifest: *manifest,
- GameDir: *gameDir, ResourceDir: *resources, ServerOrigin: *origin,
- Workers: *workers, ProbeOnly: *probeOnly,
- }, os.Stdout)
- if err != nil {
- return err
- }
- *gameDir, *resources, *origin = installed.GameDir, installed.ResourceDir, installed.ServerOrigin
- downloaded = installed.Versions
- return nil
- }},
- taskgraph.Task{Name: "base:configuration", Run: func(context.Context) error {
- if *gameDir == "" {
- *gameDir = filepath.Join(*packageDir, "game")
- }
- if *resources == "" {
- *resources = filepath.Join(*packageDir, "resources")
- }
- if *origin == "" {
- manifestPath := *manifest
- if manifestPath == "" {
- manifestPath = filepath.Join(*packageDir, "client-download.json")
- }
- defaults, err := commonconfig.Load(manifestPath, struct {
- ServerOrigin string `json:"server_origin"`
- }{}, commonconfig.DecodeOptions{AllowBOM: true, RejectTrailing: true})
- if err != nil {
- return err
- }
- *origin = defaults.ServerOrigin
- }
- var err error
- versions, err = versionconfig.Load(*versionPath)
- if err != nil {
- return err
- }
- if !*baseOnly && (versions.GameVersion != downloaded.GameVersion || versions.GameDataVersion != downloaded.GameDataVersion || versions.BundleVersion != downloaded.BundleVersion) {
- return errors.New("client package and download manifest versions differ")
- }
- return nil
- }},
- taskgraph.Task{Name: "base:settings", DependsOn: []string{"base:configuration"}, Run: func(context.Context) error {
- var err error
- settings, err = clientconfig.Normalize(clientconfig.Settings{ServerOrigin: *origin, CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: *resources})
- return err
- }},
- taskgraph.Task{Name: "base:resources", DependsOn: []string{"base:settings"}, Run: func(ctx context.Context) error {
- policyContext, cancel := context.WithTimeout(ctx, 30*time.Second)
- defer cancel()
- _, err := clientsetup.FetchResourcePolicy(policyContext, nil, settings, versions)
- return err
- }},
- taskgraph.Task{Name: "base:bepinex", DependsOn: []string{"base:resources"}, Run: func(context.Context) error {
- return download.InstallBepInEx(*packageDir, *gameDir)
- }},
- taskgraph.Task{Name: "base:patch", DependsOn: []string{"base:bepinex"}, Run: func(context.Context) error {
- _, err := clientsetup.Patch(*gameDir, settings, versions)
- return err
- }},
- taskgraph.Task{Name: "base:plugins", DependsOn: []string{"base:patch"}, Run: func(context.Context) error {
- plugins := filepath.Join(*packageDir, "plugins")
- _, err := clientsetup.InstallPlugins(*gameDir, settings, versions,
- filepath.Join(plugins, "BD2LocalIdentity.dll"), filepath.Join(plugins, "BD2LoginUI.dll"),
- filepath.Join(plugins, "BD2CashShop.dll"), filepath.Join(plugins, "BD2FChat.dll"))
- return err
- }},
- taskgraph.Task{Name: "base:preferences", DependsOn: []string{"base:plugins"}, Run: func(context.Context) error {
- return clientconfig.SavePreferences(*gameDir)
- }},
- taskgraph.Task{Name: "base", DependsOn: []string{"base:preferences"}, Run: func(context.Context) error {
- fmt.Println("Client prepared:", versions.GameVersion)
- fmt.Println("Server:", settings.ServerOrigin)
- return nil
- }},
- taskgraph.Task{Name: "prepare", DependsOn: []string{"download", "base"}},
- )
+ result, err := preparation.Run(ctx, preparation.Options{
+ PackageDirectory: *packageDir, DownloadManifest: *manifest, VersionConfig: *versionPath,
+ GameDirectory: *gameDir, ResourceDirectory: *resources,
+ Settings: clientconfig.Settings{ServerOrigin: *origin, CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: *resources},
+ Workers: *workers, DownloadOnly: *downloadOnly, BaseOnly: *baseOnly, ProbeOnly: *probeOnly, PlanOnly: *planOnly,
+ }, os.Stdout)
if err != nil {
return err
}
- target := "prepare"
- if *downloadOnly || *probeOnly {
- target = "download"
- } else if *baseOnly {
- target = "base"
- }
if *planOnly {
- plan, err := graph.Plan(target)
- if err != nil {
- return err
- }
- fmt.Println(strings.Join(plan, " -> "))
- return nil
+ fmt.Println(strings.Join(result.Plan, " -> "))
+ } else if !*downloadOnly && !*probeOnly {
+ fmt.Println("Client prepared:", result.Versions.GameVersion)
+ fmt.Println("Server:", result.Settings.ServerOrigin)
}
- return graph.Run(ctx, target)
+ return nil
}
diff --git a/go/internal/client/app/app.go b/go/internal/client/app/app.go
index d1f9a7d..d970b89 100644
--- a/go/internal/client/app/app.go
+++ b/go/internal/client/app/app.go
@@ -14,7 +14,6 @@ import (
"time"
clientconfig "bd2server/internal/client/config"
- clientdownload "bd2server/internal/client/download"
clientlayout "bd2server/internal/client/layout"
clientplugin "bd2server/internal/client/plugin"
clientsetup "bd2server/internal/client/setup"
@@ -33,6 +32,8 @@ type Options struct {
LogPath string
Versions versionconfig.Config
Development bool
+ PackageDirectory string
+ DownloadManifest string
LocalIdentityPlugin string
LoginUIPlugin string
CashShopPlugin string
@@ -85,7 +86,7 @@ type Studio struct {
cancel context.CancelFunc
mu sync.Mutex
quitOnce sync.Once
- launch func(string, string) error
+ launch func(string, string, *slog.Logger) error
savePreferences func(string) error
updates *clientupdate.Manager
}
@@ -153,7 +154,8 @@ func (s *Studio) Initialize() InitialState {
s.mu.Lock()
defer s.mu.Unlock()
state := InitialState{Platform: runtime.GOOS, ClientVersion: s.options.Versions.ClientVersion, GameVersion: s.options.Versions.GameVersion, LogPath: s.options.LogPath, GameDirectory: s.options.InitialGameDir, ServerOrigin: "http://127.0.0.1:8080", CDNMode: clientconfig.CDNOfficial}
- if state.GameDirectory == "" {
+ s.installationDefaults(&state)
+ if s.options.InitialGameDir == "" {
return state
}
if _, err := clientsetup.Inspect(state.GameDirectory, s.versions(state.GameDirectory)); err != nil {
@@ -220,8 +222,7 @@ func (s *Studio) Browse(input Request) (Response, error) {
if dir == "" {
return success("Selection cancelled", nil), nil
}
- status, err := clientsetup.Inspect(dir, s.versions(dir))
- return success("Game client found", status), err
+ return success("Installation directory selected", clientsetup.GameStatus{GameDirectory: dir}), nil
})
}
@@ -263,7 +264,7 @@ func (s *Studio) Resources(input Request) (Response, error) {
func (s *Studio) Save(input Request) (Response, error) {
return s.perform("save settings", func() (Response, error) {
- settings, err := clientsetup.SaveSettings(input.GameDirectory, input.settings(), s.versions(input.GameDirectory))
+ settings, err := clientsetup.SaveSettings(input.GameDirectory, input.settings())
if err != nil {
return Response{}, err
}
@@ -276,7 +277,10 @@ func (s *Studio) Save(input Request) (Response, error) {
func (s *Studio) Patch(input Request) (Response, error) {
return s.perform("patch client", func() (Response, error) {
- result, err := clientsetup.Patch(input.GameDirectory, input.settings(), s.versions(input.GameDirectory))
+ if _, err := clientsetup.SaveSettings(input.GameDirectory, input.settings()); err != nil {
+ return Response{}, err
+ }
+ result, err := clientsetup.Patch(input.GameDirectory)
if err != nil {
return Response{}, err
}
@@ -293,7 +297,10 @@ func (s *Studio) Patch(input Request) (Response, error) {
func (s *Studio) Install(input Request) (Response, error) {
return s.perform("install plugins", func() (Response, error) {
- result, err := clientsetup.InstallPlugins(input.GameDirectory, input.settings(), s.versions(input.GameDirectory), s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin, s.options.FChatPlugin)
+ if _, err := clientsetup.SaveSettings(input.GameDirectory, input.settings()); err != nil {
+ return Response{}, err
+ }
+ result, err := clientsetup.InstallPlugins(input.GameDirectory, s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin, s.options.FChatPlugin)
if err != nil {
return Response{}, err
}
@@ -326,9 +333,10 @@ func (s *Studio) Launch(input Request) (Response, error) {
if !status.BepInEx {
return Response{}, errors.New("install BepInEx before launching the game")
}
- ctx, cancel := context.WithTimeout(s.context(), 12*time.Second)
- defer cancel()
- if _, err := clientsetup.FetchResourcePolicy(ctx, nil, input.settings(), versions); err != nil {
+ policyCtx, cancel := context.WithTimeout(s.context(), 12*time.Second)
+ _, err = clientsetup.FetchResourcePolicy(policyCtx, nil, input.settings(), versions)
+ cancel()
+ if err != nil {
return Response{}, err
}
@@ -337,10 +345,15 @@ func (s *Studio) Launch(input Request) (Response, error) {
if s.updates != nil {
configured.Runtime = s.updates.Runtime(input.GameDirectory)
}
- settings, err := clientsetup.SaveSettings(input.GameDirectory, configured, versions)
+ settings, err := clientsetup.SaveSettings(input.GameDirectory, configured)
if err != nil {
return Response{}, err
}
+ if settings.CDNMode == clientconfig.CDNLocal {
+ if err := clientsetup.InstallLocalCatalog(input.GameDirectory, settings.LocalResourceDirectory, versions.BundleVersion); err != nil {
+ return Response{}, err
+ }
+ }
if err := s.savePreferences(input.GameDirectory); err != nil {
return Response{}, err
}
@@ -357,7 +370,7 @@ func (s *Studio) Launch(input Request) (Response, error) {
return Response{}, fmt.Errorf("install or update the client plugins before launching; %s is missing", name)
}
}
- if err := s.launch(installation.LaunchTarget(), settings.ProxyURL); err != nil {
+ if err := s.launch(installation.LaunchTarget(), settings.ProxyURL, s.log()); err != nil {
if errors.Is(err, errGameAlreadyRunning) {
return success("Brown Dust II is already running", nil), nil
}
@@ -370,7 +383,7 @@ func (s *Studio) Launch(input Request) (Response, error) {
return launch()
}
var response Response
- err = s.updates.WithLaunch(ctx, nil, status.GameDirectory, input.ServerOrigin, func() error {
+ err = s.updates.WithLaunch(s.context(), nil, status.GameDirectory, input.ServerOrigin, func() error {
var err error
response, err = launch()
return err
@@ -394,6 +407,9 @@ func (s *Studio) CheckUpdates() (Response, error) {
return Response{}, errors.New("update service is unavailable")
}
ctx := s.context()
+ if err := s.updates.WaitIdle(ctx); err != nil {
+ return Response{}, err
+ }
if err := s.updates.Check(ctx); err != nil {
return Response{}, err
}
@@ -443,39 +459,3 @@ func (s *Studio) Quit() {
}
})
}
-
-// Prepare readies an installation in one step: the required game and resource
-// update, BepInEx from the launcher package, the client patch and the plugins.
-func (s *Studio) Prepare(input Request) (Response, error) {
- return s.perform("prepare client", func() (Response, error) {
- if s.updates != nil {
- if err := s.updates.PrepareGame(s.context(), input.GameDirectory, input.ServerOrigin); err != nil {
- return Response{}, err
- }
- }
- versions := s.versions(input.GameDirectory)
- status, err := clientsetup.Inspect(input.GameDirectory, versions)
- if err != nil {
- return Response{}, err
- }
- if !status.BepInEx {
- executable, err := os.Executable()
- if err != nil {
- return Response{}, err
- }
- if err := clientdownload.InstallBepInEx(filepath.Dir(executable), status.GameDirectory); err != nil {
- return Response{}, err
- }
- }
- if _, err := clientsetup.Patch(input.GameDirectory, input.settings(), versions); err != nil {
- return Response{}, err
- }
- if _, err := clientsetup.InstallPlugins(input.GameDirectory, input.settings(), versions, s.options.LocalIdentityPlugin, s.options.LoginUIPlugin, s.options.CashShopPlugin, s.options.FChatPlugin); err != nil {
- return Response{}, err
- }
- if err := s.savePreferences(input.GameDirectory); err != nil {
- return Response{}, err
- }
- return success("Client prepared", nil), nil
- })
-}
diff --git a/go/internal/client/app/platform_darwin.go b/go/internal/client/app/platform_darwin.go
index aa84f6d..5fffce8 100644
--- a/go/internal/client/app/platform_darwin.go
+++ b/go/internal/client/app/platform_darwin.go
@@ -4,6 +4,7 @@ package app
import (
"fmt"
+ "log/slog"
"os"
"os/exec"
"path/filepath"
@@ -16,7 +17,7 @@ func ShowFatalError(err error) {
}
}
-func launchGame(target, proxyURL string) error {
+func launchGame(target, proxyURL string, _ *slog.Logger) error {
info, err := os.Stat(target)
if err != nil || !info.IsDir() || !strings.EqualFold(filepath.Ext(target), ".app") {
return fmt.Errorf("invalid macOS application bundle %q", target)
diff --git a/go/internal/client/app/platform_other.go b/go/internal/client/app/platform_other.go
index a41c8c5..f93919b 100644
--- a/go/internal/client/app/platform_other.go
+++ b/go/internal/client/app/platform_other.go
@@ -5,6 +5,7 @@ package app
import (
"errors"
"fmt"
+ "log/slog"
"os"
)
@@ -14,6 +15,6 @@ func ShowFatalError(err error) {
}
}
-func launchGame(string, string) error {
+func launchGame(string, string, *slog.Logger) error {
return errors.New("the Brown Dust II client is not supported on Linux")
}
diff --git a/go/internal/client/app/platform_windows.go b/go/internal/client/app/platform_windows.go
index e316c70..b230301 100644
--- a/go/internal/client/app/platform_windows.go
+++ b/go/internal/client/app/platform_windows.go
@@ -5,6 +5,7 @@ package app
import (
"fmt"
"log"
+ "log/slog"
"os"
"os/exec"
"path/filepath"
@@ -62,7 +63,7 @@ func visibleCommand(name string, args ...string) *exec.Cmd {
return command
}
-func launchGame(target, proxyURL string) error {
+func launchGame(target, proxyURL string, logger *slog.Logger) error {
if processID, running, err := windowsExecutableProcessID(filepath.Base(target)); err != nil {
return err
} else if running {
@@ -77,10 +78,32 @@ func launchGame(target, proxyURL string) error {
if err := command.Start(); err != nil {
return err
}
- // Unity creates the top-level window asynchronously. Best-effort foreground
- // activation prevents the new window from opening behind BD2 Launcher.
- activateProcessWindow(uint32(command.Process.Pid), 15*time.Second)
- return nil
+ pid := command.Process.Pid
+ logger.Info("game process started", "pid", pid, "executable", target)
+ finished := make(chan error, 1)
+ go func() {
+ err := command.Wait()
+ logger.Info("game process exited", "pid", pid, "exit_code", command.ProcessState.ExitCode(), "error", err)
+ finished <- err
+ }()
+ deadline := time.NewTimer(30 * time.Second)
+ defer deadline.Stop()
+ ticker := time.NewTicker(100 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ select {
+ case err := <-finished:
+ return fmt.Errorf("game exited before showing a window: pid=%d exit_code=%d error=%v; see Player.log", pid, command.ProcessState.ExitCode(), err)
+ case <-deadline.C:
+ return fmt.Errorf("game process is running without a visible window after 30 seconds: pid=%d; see Player.log", pid)
+ case <-ticker.C:
+ if topLevelWindowForProcess(uint32(pid)) != 0 {
+ activateProcessWindow(uint32(pid), 0)
+ logger.Info("game window ready", "pid", pid)
+ return nil
+ }
+ }
+ }
}
func windowsExecutableProcessID(name string) (uint32, bool, error) {
diff --git a/go/internal/client/app/prepare.go b/go/internal/client/app/prepare.go
new file mode 100644
index 0000000..a3cd85c
--- /dev/null
+++ b/go/internal/client/app/prepare.go
@@ -0,0 +1,78 @@
+package app
+
+import (
+ "context"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime"
+
+ clientconfig "bd2server/internal/client/config"
+ "bd2server/internal/client/preparation"
+ commonconfig "bd2server/internal/common/config"
+ "bd2server/internal/common/versionconfig"
+)
+
+func (s *Studio) packageDirectory() (string, error) {
+ if s.options.PackageDirectory != "" {
+ return filepath.Abs(s.options.PackageDirectory)
+ }
+ executable, err := os.Executable()
+ return filepath.Dir(executable), err
+}
+
+func (s *Studio) downloadManifest(directory string) string {
+ if s.options.DownloadManifest != "" {
+ return s.options.DownloadManifest
+ }
+ return filepath.Join(directory, "client-download.json")
+}
+
+func (s *Studio) installationDefaults(state *InitialState) {
+ directory, err := s.packageDirectory()
+ if err != nil {
+ return
+ }
+ defaults, err := commonconfig.Load(s.downloadManifest(directory), struct {
+ ServerOrigin string `json:"server_origin"`
+ }{}, commonconfig.DecodeOptions{AllowBOM: true, RejectTrailing: true})
+ if err == nil {
+ if origin, err := clientconfig.NormalizeOrigin(defaults.ServerOrigin); err == nil {
+ state.ServerOrigin = origin
+ }
+ }
+ if runtime.GOOS == "windows" && state.GameDirectory == "" {
+ state.GameDirectory = filepath.Join(directory, "game")
+ state.CDNMode = clientconfig.CDNLocal
+ }
+ state.LocalResourceDirectory = filepath.Join(directory, "resources")
+}
+
+func (s *Studio) Prepare(input Request) (Response, error) {
+ return s.perform("prepare client", func() (Response, error) {
+ directory, err := s.packageDirectory()
+ if err != nil {
+ return Response{}, err
+ }
+ result, err := preparation.Run(s.context(), preparation.Options{
+ PackageDirectory: directory, DownloadManifest: s.downloadManifest(directory),
+ GameDirectory: input.GameDirectory, Settings: input.settings(), Versions: s.versions(input.GameDirectory),
+ Workers: 8, DownloadIfMissing: true,
+ LocalIdentityPlugin: s.options.LocalIdentityPlugin, LoginUIPlugin: s.options.LoginUIPlugin,
+ CashShopPlugin: s.options.CashShopPlugin, FChatPlugin: s.options.FChatPlugin,
+ SavePreferences: s.savePreferences,
+ PrepareGame: func(ctx context.Context, game string, settings clientconfig.Settings) (versionconfig.Config, error) {
+ if s.updates != nil {
+ if err := s.updates.PrepareGame(ctx, game, settings.ServerOrigin); err != nil {
+ return versionconfig.Config{}, err
+ }
+ }
+ return s.versions(game), nil
+ },
+ }, io.Discard)
+ if err != nil {
+ return Response{}, err
+ }
+ return success("Client prepared", result.Status), nil
+ })
+}
diff --git a/go/internal/client/app/web/index.html b/go/internal/client/app/web/index.html
index 85888bf..c9d59ee 100644
--- a/go/internal/client/app/web/index.html
+++ b/go/internal/client/app/web/index.html
@@ -12,14 +12,14 @@
*{box-sizing:border-box}body{margin:0;background:#e7dcc7;color:var(--ink);font:14px/1.65 var(--sans);overflow-x:hidden}button,input{font:inherit}button{cursor:pointer}button:disabled{cursor:wait;opacity:.5}button,input,a{-webkit-tap-highlight-color:transparent}button:focus-visible,input:focus-visible,summary:focus-visible{outline:2px solid var(--rust);outline-offset:5px}[hidden]{display:none!important}::selection{background:#b9764c;color:#fff9ef}
.landscape{position:fixed;inset:0;z-index:-3;background:linear-gradient(130deg,#f1e9d9 0%,#e7d5b6 42%,#bc8665 100%);overflow:hidden}.landscape svg{position:absolute;width:100%;height:100%;transition:transform 2s var(--ease),opacity 1.6s;transform:scale(1.04);opacity:.87}.landscape:after{content:'';position:absolute;inset:0;background:linear-gradient(90deg,rgba(244,237,222,.8),rgba(240,228,207,.2) 65%,transparent),linear-gradient(0deg,rgba(73,48,31,.14),transparent 48%)}body[data-scene=server] .landscape svg{transform:scale(1.14) translateX(-2%)}body[data-scene=desk] .landscape svg{transform:scale(1.2) translateY(-3%);opacity:.27}body[data-scene=desk] .landscape:after{background:rgba(240,234,221,.55)}
.grain{position:fixed;inset:0;pointer-events:none;z-index:20;opacity:.038;background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 180 180' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='grain'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.82' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Cpath fill='%23000' filter='url(%23grain)' d='M0 0h180v180H0z'/%3E%3C/svg%3E")}.sunlight{position:fixed;inset:-40%;pointer-events:none;z-index:-2;background:radial-gradient(ellipse at 70% 23%,#fff7d777,transparent 38%);animation:drift 18s ease-in-out infinite alternate}
-.topbar{height:94px;max-width:1440px;margin:auto;padding:0 58px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);gap:24px}.brand{display:flex;gap:13px;align-items:center;flex-shrink:0}.emblem{display:block;width:40px;height:40px;flex-shrink:0}.brand-name{font-size:13px;letter-spacing:.19em;line-height:1.4}.brand-name small{display:block;font-size:9px;letter-spacing:.28em;color:var(--muted);margin-top:4px}.top-note{font-size:11px;color:var(--muted);letter-spacing:.07em}.text-btn{background:none;border:0;color:var(--muted);padding:8px 0;border-bottom:1px solid transparent}.text-btn:hover{color:var(--rust);border-bottom-color:var(--rust)}
-main{max-width:1324px;margin:auto;padding:0 58px}.scene{position:relative}.intro-scene{min-height:calc(100svh - 178px);display:grid;grid-template-columns:1.1fr .9fr;align-items:center;gap:8%;padding:66px 0 82px}.eyebrow{font-size:10px;letter-spacing:.22em;text-transform:uppercase;display:flex;align-items:center;gap:12px;color:#81634c;margin-bottom:24px}.eyebrow:before{content:'';height:1px;width:32px;background:currentColor}h1,h2,h3,p{margin:0}h1{font:400 clamp(42px,4.8vw,68px)/1.28 var(--serif);letter-spacing:.035em}.lead{max-width:380px;font-size:14px;color:var(--muted);line-height:1.95;margin-top:26px}.intro-label{display:flex;gap:14px;align-items:center;margin-top:44px;font-size:11px;color:#8a7059}.intro-label i{height:1px;width:30px;background:#987759}.form-card{position:relative;background:linear-gradient(135deg,rgba(250,246,237,.89),rgba(238,225,203,.7));border:1px solid rgba(255,255,255,.6);box-shadow:0 24px 70px -35px #65472c77,inset 0 0 0 1px rgba(116,89,55,.035);backdrop-filter:blur(24px);border-radius:4px;padding:34px 32px}.card-number{font:italic 46px/1 var(--serif);color:#b2997e;opacity:.6;margin-bottom:30px}.form-card h2{font:400 23px var(--serif);margin-bottom:9px}.description{font-size:12px;line-height:1.8;color:var(--muted);margin-bottom:26px}code{font:11px/1.8 Consolas,monospace;overflow-wrap:anywhere}label.field-label{display:block;font-size:11px;margin-bottom:9px;color:#6f5c49}.input-row{display:flex;gap:8px}input[type=text]{width:100%;min-width:0;border:1px solid #aa927755;border-radius:3px;padding:13px 12px;background:#fffcf57d;color:var(--ink);outline:none;transition:background .2s,border-color .2s;font-size:12px}input[type=text]:focus{border-color:var(--rust);background:#fffaf0}.btn{border:1px solid #81664a55;border-radius:3px;padding:11px 18px;display:inline-flex;align-items:center;justify-content:center;gap:12px;min-height:43px;background:#fffcf533;color:var(--ink);transition:background .25s,box-shadow .25s,transform .25s;white-space:nowrap;font-size:12px}.btn:hover:not(:disabled){background:#fff9eb99;transform:translateY(-2px)}.btn.primary{background:#4b3a2c;color:#fff5e4;border-color:#4b3a2c}.btn.primary:hover:not(:disabled){background:#654932;box-shadow:0 6px 17px #4b3a2c24}.btn.rust{background:#985e40;color:#fff6e8;border-color:#985e40}.btn.rust:hover:not(:disabled){background:#ad6c49}.arrow{font-size:20px;font-weight:300;line-height:1}.wide{width:100%;justify-content:space-between;margin-top:28px;padding:14px 18px}.small-note{font-size:11px;color:#877460;margin-top:12px;line-height:1.8}.inline-result{font-size:11px;min-height:22px;margin-top:10px;color:var(--muted)}.inline-result.error{color:var(--bad)}.form-tools{display:flex;align-items:center;justify-content:space-between;margin-top:4px;gap:8px;font-size:11px}.server-back{margin-top:14px;text-align:center}.server-back .text-btn{font-size:11px}.bottom-bar{max-width:1324px;margin:auto;padding:0 58px 28px;display:flex;justify-content:space-between;align-items:center;gap:24px}.steps{display:flex;list-style:none;padding:0;margin:0;gap:26px;font-size:11px;color:#8f7d69}.steps li{display:flex;gap:8px;align-items:center}.steps .num{font:italic 14px var(--serif)}.steps li.active{color:#503b2b}.steps li.active:after{content:'';width:19px;height:1px;background:#86573b}.bottom-note{font-size:10px;color:#897963;letter-spacing:.04em}
+.topbar{height:94px;max-width:1440px;margin:auto;padding:0 58px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);gap:24px}.brand{display:flex;gap:13px;align-items:center;flex-shrink:0}.emblem{display:block;width:40px;height:40px;flex-shrink:0}.brand-name{font-size:13px;letter-spacing:.19em;line-height:1.4}.brand-name small{display:block;font-size:9px;letter-spacing:.28em;color:var(--muted);margin-top:4px}.text-btn{background:none;border:0;color:var(--muted);padding:8px 0;border-bottom:1px solid transparent}.text-btn:hover{color:var(--rust);border-bottom-color:var(--rust)}
+main{max-width:1324px;margin:auto;padding:0 58px}.scene{position:relative}.intro-scene{min-height:calc(100svh - 178px);display:grid;grid-template-columns:1.1fr .9fr;align-items:center;gap:8%;padding:66px 0 82px}.eyebrow{font-size:10px;letter-spacing:.22em;text-transform:uppercase;display:flex;align-items:center;gap:12px;color:#81634c;margin-bottom:24px}.eyebrow:before{content:'';height:1px;width:32px;background:currentColor}h1,h2,h3,p{margin:0}h1{font:400 clamp(42px,4.8vw,68px)/1.28 var(--serif);letter-spacing:.035em}.lead{max-width:380px;font-size:14px;color:var(--muted);line-height:1.95;margin-top:26px}.intro-label{display:flex;gap:14px;align-items:center;margin-top:44px;font-size:11px;color:#8a7059}.intro-label i{height:1px;width:30px;background:#987759}.form-card{position:relative;background:linear-gradient(135deg,rgba(250,246,237,.89),rgba(238,225,203,.7));border:1px solid rgba(255,255,255,.6);box-shadow:0 24px 70px -35px #65472c77,inset 0 0 0 1px rgba(116,89,55,.035);backdrop-filter:blur(24px);border-radius:4px;padding:34px 32px}.card-number{font:italic 46px/1 var(--serif);color:#b2997e;opacity:.6;margin-bottom:30px}.form-card h2{font:400 23px var(--serif);margin-bottom:9px}.description{font-size:12px;line-height:1.8;color:var(--muted);margin-bottom:26px}code{font:11px/1.8 Consolas,monospace;overflow-wrap:anywhere}label.field-label{display:block;font-size:11px;margin-bottom:9px;color:#6f5c49}.input-row{display:flex;gap:8px}.input-row>.btn{flex-shrink:0}input[type=text]{width:100%;min-width:0;border:1px solid #aa927755;border-radius:3px;padding:13px 12px;background:#fffcf57d;color:var(--ink);outline:none;transition:background .2s,border-color .2s;font-size:12px}input[type=text]:focus{border-color:var(--rust);background:#fffaf0}.btn{border:1px solid #81664a55;border-radius:3px;padding:11px 18px;display:inline-flex;align-items:center;justify-content:center;gap:12px;min-height:43px;background:#fffcf533;color:var(--ink);transition:background .25s,box-shadow .25s,transform .25s;white-space:nowrap;font-size:12px}.btn:hover:not(:disabled){background:#fff9eb99;transform:translateY(-2px)}.btn.primary{background:#4b3a2c;color:#fff5e4;border-color:#4b3a2c}.btn.primary:hover:not(:disabled){background:#654932;box-shadow:0 6px 17px #4b3a2c24}.btn.rust{background:#985e40;color:#fff6e8;border-color:#985e40}.btn.rust:hover:not(:disabled){background:#ad6c49}.arrow{font-size:20px;font-weight:300;line-height:1}.wide{width:100%;justify-content:space-between;margin-top:28px;padding:14px 18px}.small-note{font-size:11px;color:#877460;margin-top:12px;line-height:1.8}.inline-result{font-size:11px;min-height:22px;margin-top:10px;color:var(--muted)}.inline-result.error{color:var(--bad)}.form-tools{display:flex;align-items:center;justify-content:space-between;margin-top:4px;gap:8px;font-size:11px}.server-back{margin-top:14px;text-align:center}.server-back .text-btn{font-size:11px}.bottom-bar{max-width:1324px;margin:auto;padding:0 58px 28px;display:flex;justify-content:space-between;align-items:center;gap:24px}.steps{display:flex;list-style:none;padding:0;margin:0;gap:26px;font-size:11px;color:#8f7d69}.steps li{display:flex;gap:8px;align-items:center}.steps .num{font:italic 14px var(--serif)}.steps li.active{color:#503b2b}.steps li.active:after{content:'';width:19px;height:1px;background:#86573b}.bottom-note{font-size:10px;color:#897963;letter-spacing:.04em}
.scene.is-entering .reveal{animation:reveal 1.3s var(--ease) both;animation-delay:calc(var(--i,0)*110ms)}.scene.is-leaving{animation:leave .55s cubic-bezier(.4,0,.6,1) both;pointer-events:none}.transition-veil{position:fixed;inset:0;background:linear-gradient(115deg,#eee4d4ed,#dfc7a8e8);z-index:30;pointer-events:none;opacity:0;backdrop-filter:blur(8px)}.transition-veil.play{animation:veil 1.25s ease-in-out both}.opening-curtain{position:fixed;inset:0;background:#e8decc;pointer-events:none;z-index:40;animation:opening 1.65s ease forwards}
.desk-scene{padding:46px 0 34px}.desk-header{display:flex;justify-content:space-between;align-items:end;gap:24px;margin-bottom:30px}.desk-header .eyebrow{margin-bottom:13px}.desk-header h1{font-size:42px}.desk-header p{margin-top:12px;font-size:12px;color:var(--muted)}.connection-chip{display:flex;align-items:center;gap:9px;font-size:11px;color:#74634f;border:1px solid var(--line);padding:8px 13px;border-radius:30px}.dot{width:6px;height:6px;border-radius:50%;background:#a99b85;display:inline-block;flex-shrink:0}.dot.good{background:var(--olive);box-shadow:0 0 0 4px #68744912}.dot.bad{background:var(--bad)}.desk-grid{display:grid;grid-template-columns:minmax(0,1fr) 298px;gap:24px}.main-panel{background:#f9f5ec94;border:1px solid #fff9;border-radius:4px;box-shadow:0 12px 50px -40px #5c412c55}.panel-section{padding:25px 28px;border-bottom:1px solid var(--line)}.panel-section:last-child{border-bottom:0}.section-title{display:flex;align-items:center;gap:11px;margin-bottom:22px}.section-title .index{font:italic 14px var(--serif);color:#a08569}.section-title h2{font-size:15px;font-weight:500}.section-title .end{margin-left:auto;font-size:10px;color:var(--muted)}.setting-row{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-top:18px}.setting-name{font-size:10px;color:var(--muted);margin-bottom:4px}.setting-value{font-size:12px;overflow-wrap:anywhere}.setting-row>div{min-width:0}.setting-row .text-btn{font-size:11px;flex-shrink:0;color:var(--rust)}.route-options{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}.route{position:relative;cursor:pointer}.route input{position:absolute;opacity:0;inset:0;width:100%;height:100%;margin:0}.route-content{display:block;position:relative;pointer-events:none;min-height:139px;padding:15px 14px;border:1px solid var(--line);border-radius:3px;transition:.25s;background:#f8f3e83d}.route-content .route-top{display:flex;align-items:center;justify-content:space-between;margin-bottom:16px}.route-code{font:10px var(--serif);letter-spacing:.08em;color:#98826b}.radio-dot{width:11px;height:11px;border-radius:50%;border:1px solid #aa9680;display:block}.route-content strong{font-size:12px;font-weight:500;display:block;margin-bottom:5px}.route-content small{font-size:10px;line-height:1.75;display:block;color:var(--muted)}.route input:checked+.route-content{border-color:#9e7551;background:#b9986920;box-shadow:inset 0 0 0 1px #9e755118}.route input:checked+.route-content .radio-dot{background:#916c4a;border:3px solid #e8d9c3;box-shadow:0 0 0 1px #916c4a}.route input:focus-visible+.route-content{outline:2px solid var(--rust);outline-offset:4px}.route input:disabled+.route-content{opacity:.55}.route-actions{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:18px}.route-actions .text-btn{font-size:11px}.route-hint{font-size:10px;color:#927d64;margin-top:13px}.policy{font:11px/1.9 Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere;background:#dfd2bc50;border-left:2px solid #a3835e;padding:13px;margin-top:16px}.prepare-note{font-size:11px;color:var(--muted);margin:-8px 0 19px;line-height:1.8}.prepare-actions{display:flex;gap:10px;flex-wrap:wrap}.prepare-actions .btn{flex:1}.status-panel{align-self:start;padding:25px 23px;background:#dfd1ba66;border:1px solid #9875501c;border-radius:4px}.status-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:6px}.status-title h2{font:400 19px var(--serif)}.status-title span{font-size:9px;color:#927d65;letter-spacing:.1em}.check{display:flex;align-items:center;justify-content:space-between;padding:14px 0;border-bottom:1px solid var(--line);font-size:11px;gap:8px}.check span:last-child{color:#948471;font-size:10px}.check span.ok{color:var(--olive)}.check span.warn{color:var(--bad)}.status-foot{font-size:10px;color:#8d7a63;margin-top:14px;line-height:1.8}.log-wrap{border-top:1px solid var(--line);margin-top:24px;padding-top:19px}.log-heading{font-size:10px;color:#8d745b;display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}.log{font-size:11px;color:#7e6c56;line-height:1.8;overflow-wrap:anywhere;min-height:65px}.log strong{display:block;color:var(--ink);font-size:12px;font-weight:500;margin-bottom:5px}.history{margin-top:14px;border-top:1px solid var(--line);padding-top:12px;font-size:10px;color:#806e59}.history summary{cursor:pointer}.history ol{list-style:none;padding:0;margin:10px 0 0;max-height:180px;overflow:auto}.history li{padding:7px 0;border-top:1px solid #a487651a;overflow-wrap:anywhere}.history time{display:block;color:#9a876f;font-size:9px}.history li.error{color:var(--bad)}.unsaved{font-size:10px;color:var(--rust);margin-top:12px}.desk-footer{display:flex;justify-content:space-between;gap:20px;margin-top:24px;color:#8a765e;font-size:10px}
.desk-actions{display:flex;align-items:center;gap:10px;flex-wrap:wrap;justify-content:flex-end}.desk-actions .btn{min-height:38px;padding:8px 16px}.local-resource{margin-top:14px;padding:14px;border:1px solid var(--line);background:#f8f3e83d;border-radius:3px}.local-resource[hidden]{display:none}.local-resource .small-note{margin:8px 0 0}
.update-box{display:grid;gap:4px;margin-top:12px;padding:10px 12px;border:1px solid #c9ac8288;border-radius:3px;background:#fff8ec80;font-size:12px}.update-box span{white-space:pre-line;max-height:120px;overflow:auto;color:#6d5a47}.update-box .text-btn{justify-self:start}.toast{position:fixed;bottom:28px;left:50%;transform:translate(-50%,18px);max-width:min(590px,calc(100% - 32px));width:max-content;padding:13px 21px;background:#483a2e;color:#fff4e0;box-shadow:0 10px 40px #483a2e26;border:1px solid #c9ac82;border-radius:3px;font-size:12px;opacity:0;pointer-events:none;transition:.35s var(--ease);z-index:70}.toast.show{opacity:1;transform:translate(-50%,0)}.toast.error{background:#793e30;color:#fff0e3}dialog{width:min(490px,calc(100% - 32px));padding:30px;border:1px solid #fff9;border-radius:5px;background:#f0e7d7;color:var(--ink);box-shadow:0 30px 140px #37271955}dialog::backdrop{background:#40322266;backdrop-filter:blur(9px)}dialog[open]{animation:reveal .55s var(--ease)}.dialog-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:25px}.dialog-head h2{font:24px var(--serif)}.dialog-close{background:none;border:0;font-size:23px;color:var(--muted);padding:0 7px}.dialog-actions{display:flex;justify-content:flex-end;margin-top:20px}.quit-scene{min-height:65svh;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center}.quit-scene h1{font-size:44px}.quit-scene p{color:var(--muted);margin-top:20px;font-size:13px}
@keyframes reveal{from{opacity:0;filter:blur(10px);transform:translateY(24px) scale(.986)}to{opacity:1;filter:blur(0);transform:none}}@keyframes leave{to{opacity:0;filter:blur(8px);transform:translateY(-15px) scale(1.014)}}@keyframes veil{0%,100%{opacity:0}45%,58%{opacity:1}}@keyframes opening{0%,15%{opacity:1}100%{opacity:0}}@keyframes drift{to{transform:translate(-4%,3%) scale(1.05)}}
-@media(min-width:1500px){.intro-scene{gap:13%}.form-card{padding:40px}.intro-scene h1{font-size:72px}}@media(max-width:1050px){.topbar{padding:0 30px}main,.bottom-bar{padding-left:30px;padding-right:30px}.intro-scene{gap:5%}.form-card{padding:27px 23px}.desk-grid{grid-template-columns:minmax(0,1fr) 250px;gap:16px}.panel-section{padding:23px 20px}.status-panel{padding:23px 18px}.route-content{padding:12px 10px}.top-note{display:none}}@media(max-width:760px){.topbar{height:77px;padding:0 22px}main,.bottom-bar{padding-left:22px;padding-right:22px}.intro-scene{grid-template-columns:1fr;gap:32px;padding:42px 0;min-height:auto}.intro-scene h1{font-size:43px}.eyebrow{margin-bottom:17px}.lead{margin-top:18px;max-width:100%}.intro-label{display:none}.form-card{padding:25px}.card-number{position:absolute;right:25px;top:25px;font-size:31px}.form-card h2{padding-right:45px}.bottom-bar{align-items:start;flex-direction:column;gap:15px}.steps{gap:21px}.desk-scene{padding-top:31px}.desk-header{align-items:start}.desk-header h1{font-size:34px}.connection-chip{font-size:10px;padding:6px 10px;margin-top:4px}.desk-grid{grid-template-columns:1fr}.status-panel{display:grid;grid-template-columns:1fr 1fr;gap:0 30px}.status-title{grid-column:1/-1}.log-wrap{margin-top:10px;border-top:0}.status-foot{margin-bottom:14px}.desk-footer{flex-direction:column;gap:7px}.bottom-note{font-size:9px}.landscape svg{width:180%;left:-60%}.desk-header p{max-width:240px}.route-content{min-height:145px}}@media(max-width:400px){main,.bottom-bar{padding-left:16px;padding-right:16px}.form-card{padding:23px 18px}.route-options{grid-template-columns:1fr}.route-content{min-height:0;padding:12px 14px}.route-content .route-top{float:right;margin:0 0 10px 20px;gap:12px}.route-content small{max-width:90%}.status-panel{display:block}.desk-header{flex-direction:column;gap:14px}.panel-section{padding:22px 16px}.btn{padding-left:13px;padding-right:13px}.steps{gap:15px}.route-actions{align-items:stretch}.prepare-actions{flex-direction:column}}
+@media(min-width:1500px){.intro-scene{gap:13%}.form-card{padding:40px}.intro-scene h1{font-size:72px}}@media(max-width:1050px){.topbar{padding:0 30px}main,.bottom-bar{padding-left:30px;padding-right:30px}.intro-scene{gap:5%}.form-card{padding:27px 23px}.desk-grid{grid-template-columns:minmax(0,1fr) 250px;gap:16px}.panel-section{padding:23px 20px}.status-panel{padding:23px 18px}.route-content{padding:12px 10px}}@media(max-width:760px){.topbar{height:77px;padding:0 22px}main,.bottom-bar{padding-left:22px;padding-right:22px}.intro-scene{grid-template-columns:1fr;gap:32px;padding:42px 0;min-height:auto}.intro-scene h1{font-size:43px}.eyebrow{margin-bottom:17px}.lead{margin-top:18px;max-width:100%}.intro-label{display:none}.form-card{padding:25px}.card-number{position:absolute;right:25px;top:25px;font-size:31px}.form-card h2{padding-right:45px}.bottom-bar{align-items:start;flex-direction:column;gap:15px}.steps{gap:21px}.desk-scene{padding-top:31px}.desk-header{align-items:start}.desk-header h1{font-size:34px}.connection-chip{font-size:10px;padding:6px 10px;margin-top:4px}.desk-grid{grid-template-columns:1fr}.status-panel{display:grid;grid-template-columns:1fr 1fr;gap:0 30px}.status-title{grid-column:1/-1}.log-wrap{margin-top:10px;border-top:0}.status-foot{margin-bottom:14px}.desk-footer{flex-direction:column;gap:7px}.bottom-note{font-size:9px}.landscape svg{width:180%;left:-60%}.desk-header p{max-width:240px}.route-content{min-height:145px}}@media(max-width:400px){main,.bottom-bar{padding-left:16px;padding-right:16px}.form-card{padding:23px 18px}.route-options{grid-template-columns:1fr}.route-content{min-height:0;padding:12px 14px}.route-content .route-top{float:right;margin:0 0 10px 20px;gap:12px}.route-content small{max-width:90%}.status-panel{display:block}.desk-header{flex-direction:column;gap:14px}.panel-section{padding:22px 16px}.btn{padding-left:13px;padding-right:13px}.steps{gap:15px}.route-actions{align-items:stretch}.prepare-actions{flex-direction:column}}
@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important;scroll-behavior:auto!important}.opening-curtain{display:none}}
.proxy-select{width:100%;padding:12px 14px;border:1px solid var(--line);border-radius:3px;background:#f8f3e8;color:var(--ink);font:inherit}#proxyURL{width:100%}/* Window chrome belongs to the page; keep scrolling without a visible gutter. */
html,body{scrollbar-width:none}html::-webkit-scrollbar,body::-webkit-scrollbar{display:none}
@@ -38,11 +38,11 @@ html:lang(ja){--sans:'Segoe UI','Yu Gothic UI',Meiryo,sans-serif;--serif:Georgia
-
+
@@ -99,7 +99,7 @@ let scene='directory',busy=false,transitioning=false,toastTimer,editorKind=null,
const status={executable:null,resources:null,bepinex:null,config:null};
function payload(){const mode=document.querySelector('input[name="cdn"]:checked').value;return{game_directory:$('gameDir').value.trim(),server_origin:$('origin').value.trim(),cdn_mode:mode,local_resource_directory:mode==='local'?$('localResourceDir').value.trim():'',proxy_url:$('proxyMode').value==='manual'?$('proxyURL').value.trim():''}}
function signature(){return JSON.stringify({...payload(),proxy_mode:$('proxyMode').value})}
-const backendKeys={'Update check completed':'backend.update_checked','Launcher is restarting to finish the update':'backend.launcher_restarting','update service is unavailable':'backend.update_unavailable','Another update operation is in progress':'backend.update_busy','No launcher update is available':'backend.no_launcher_update','The launcher update has not finished downloading':'backend.launcher_update_incomplete','The launcher is updating; start the game after it finishes':'backend.launcher_updating','The game is running; its plugins update after it exits':'backend.game_running_plugins','The server is updating; try again after it finishes':'backend.server_maintenance','Selection cancelled':'backend.selection_cancelled','Game client found':'backend.game_found','Local resource directory found':'backend.local_resources_found','Game directory is valid':'backend.directory_valid','The client will use the release-locked official CDN':'backend.official_cdn','Local resources verified':'backend.local_verified','Server resource policy verified':'backend.server_policy_verified','Connection settings saved':'backend.settings_saved','Client prepared':'backend.prepared','Client entry point patched; the original backup was retained':'backend.patched','Client patch is already complete; no asset file was rewritten':'backend.patch_current','BD2 client plugins installed or updated':'backend.plugins_installed','BD2 client plugins are already up to date; no DLL was rewritten':'backend.plugins_current','Brown Dust II started':'backend.game_started','Brown Dust II is already running':'backend.game_running','Client tool exited':'backend.tool_exited'};
+const backendKeys={'Update check completed':'backend.update_checked','Launcher is restarting to finish the update':'backend.launcher_restarting','update service is unavailable':'backend.update_unavailable','Another update operation is in progress':'backend.update_busy','No launcher update is available':'backend.no_launcher_update','The launcher update has not finished downloading':'backend.launcher_update_incomplete','The launcher is updating; start the game after it finishes':'backend.launcher_updating','The game is running; its plugins update after it exits':'backend.game_running_plugins','The server is updating; try again after it finishes':'backend.server_maintenance','Selection cancelled':'backend.selection_cancelled','Game client found':'backend.game_found','Installation directory selected':'backend.directory_selected','Local resource directory found':'backend.local_resources_found','Game directory is valid':'backend.directory_valid','The client will use the release-locked official CDN':'backend.official_cdn','Local resources verified':'backend.local_verified','Server resource policy verified':'backend.server_policy_verified','Connection settings saved':'backend.settings_saved','Client prepared':'backend.prepared','Client entry point patched; the original backup was retained':'backend.patched','Client patch is already complete; no asset file was rewritten':'backend.patch_current','BD2 client plugins installed or updated':'backend.plugins_installed','BD2 client plugins are already up to date; no DLL was rewritten':'backend.plugins_current','Brown Dust II started':'backend.game_started','Brown Dust II is already running':'backend.game_running','Client tool exited':'backend.tool_exited'};
const PLUGINS_REJECTED=/^Server (\S+) no longer accepts these plugins: (.+)\. Update the plugins in the launcher first$/;
const pluginList=list=>({getString:async ()=>(await Promise.all(list.split(', ').map(async item=>{const m=/^(.+) (\S+) \(needs (\S+)\)$/.exec(item);return m?await dynamicText('backend.plugin_requirement',m[1],m[2],m[3]):item}))).join(t('common.list_separator'))});
const GAME_MISMATCH=/^Server game version (\S+) does not match client game version (\S+)$/;
@@ -137,13 +137,13 @@ $('gameDir').addEventListener('input',async ()=>await invalidate(true));$('origi
$('browse').onclick=async ()=>await action('browse',async()=>{const previous=payload().game_directory;const r=await api('browse',{...payload(),dialog_title:t('launcher.dialog.game_directory')});if(r.data){await applyStatus(r.data);if(payload().game_directory!==previous)$('policy').hidden=true}await show(r.text)});
$('browseResources').onclick=async ()=>await action('browseResources',async()=>{const r=await api('browseResources',{...payload(),dialog_title:t('launcher.dialog.resource_directory')});if(r.data){$('localResourceDir').value=r.data.local_directory||'';await invalidate()}await show(r.text)});
$('inspect').onclick=async ()=>await action('inspect',inspect);$('refresh').onclick=async ()=>await action('refresh',inspect);
-$('directoryNext').onclick=async ()=>await action('directoryNext',async()=>{await inspect();await sync();await navigateScene('server')});
+$('directoryNext').onclick=async ()=>await action('directoryNext',async()=>{requireDirectory();await sync();await navigateScene('server')});
$('serverBack').onclick=async ()=>{if(!busy)await navigateScene('directory')};
$('serverNext').onclick=async ()=>await action('serverNext',async()=>{await requireOrigin();await sync();await navigateScene('desk')});
$('checkResources').onclick=async ()=>await action('checkResources',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('resources',payload()),p=r.data||{},local=payload().local_resource_directory,v=value=>value||t('launcher.resources.missing');$('policy').hidden=false;await put('policy',{getString:()=>p.mode==='official'?`${t('launcher.resources.official.code')} · ${t('launcher.resources.policy_official')}`:p.mode==='local'?`${t('launcher.resources.local.code')} · ${p.local_directory||local}\nServerData · ${v(p.server_data_url)}\nGameData · ${v(p.game_data_url)}`:`${t('launcher.resources.server.code')} · ${t('launcher.resources.policy_server')}\nServerData · ${v(p.server_data_url)}\nGameData · ${v(p.game_data_url)}\nBundle · ${v(p.bundle_version)}\nGameData · ${v(p.game_data_version)}`});await show(r.text)});
async function saved(){savedSignature=signature();status.config=true;await sync()}
$('save').onclick=async ()=>await action('save',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('save',payload());await saved();await show(r.text)});
-$('prepare').onclick=async ()=>await action('prepare',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('prepare',payload());status.bepinex=true;await saved();await show(r.text)});
+$('prepare').onclick=async ()=>await action('prepare',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('prepare',payload());await applyStatus(r.data);await saved();await show(r.text)});
$('patch').onclick=async ()=>await action('patch',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('patch',payload());await saved();await show(r.text)});
$('install').onclick=async ()=>await action('install',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('install',payload());status.bepinex=true;await saved();await show(r.text)});
$('launch').onclick=async ()=>await action('launch',async()=>{requireDirectory();await requireOrigin();requireResources();await requireProxy();const r=await api('launch',payload());await saved();await show(r.text)});
@@ -153,7 +153,7 @@ $('windowMaximise').onclick=()=>window.runtime?.WindowToggleMaximise();
document.querySelector('.topbar').ondblclick=e=>{if(!e.target.closest('.window-controls,.lang-select'))window.runtime?.WindowToggleMaximise()};
$('windowClose').onclick=async ()=>{clearTimeout(toastTimer);try{bridge().Quit().catch(async error=>await show(problemText(error),true))}catch(error){await show(problemText(error),true)}};
$('gameDir').addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();(editorKind?$('inspect'):$('directoryNext')).click()}});$('origin').addEventListener('keydown',e=>{if(e.key==='Enter'){e.preventDefault();(editorKind?$('doneEditor'):$('serverNext')).click()}});
-async function initialize(){setBusy(true);try{const initial=await bridge().Initialize();HOST_PLATFORM=initial.platform;INITIAL_CDN=initial.cdn_mode;AUTO_OPEN=initial.auto_open;$('gameDir').value=initial.game_directory||'';$('origin').value=initial.server_origin||'http://127.0.0.1:8080';$('localResourceDir').value=initial.local_resource_directory||'';$('proxyURL').value=initial.proxy_url||'';$('proxyMode').value=initial.proxy_url?'manual':'direct';$('clientReleaseVersion').textContent=initial.client_version||'';$('gameReleaseVersion').textContent=initial.game_version||'';$('persistentLogPath').textContent=initial.log_path||'';const initialRadio=document.querySelector(`input[name="cdn"][value="${CSS.escape(INITIAL_CDN)}"]`);if(initialRadio)initialRadio.checked=true;if(HOST_PLATFORM==='darwin'){const description=$('directoryDescription');$('gameDir').dataset.i18nAttr='placeholder:launcher.directory.placeholder_mac';description.dataset.i18n='launcher.directory.description_mac';description.dataset.i18nCode='BrownDust II.app';await applyStatic()}await sync();if($('gameDir').value.trim()){await inspect();if(AUTO_OPEN){await saved();await navigateScene('desk')}}}catch(error){await show(problemText(error),true)}finally{setBusy(false)}}
+async function initialize(){setBusy(true);try{const initial=await bridge().Initialize();HOST_PLATFORM=initial.platform;INITIAL_CDN=initial.cdn_mode;AUTO_OPEN=initial.auto_open;$('gameDir').value=initial.game_directory||'';$('origin').value=initial.server_origin||'http://127.0.0.1:8080';$('localResourceDir').value=initial.local_resource_directory||'';$('proxyURL').value=initial.proxy_url||'';$('proxyMode').value=initial.proxy_url?'manual':'direct';$('clientReleaseVersion').textContent=initial.client_version||'';$('gameReleaseVersion').textContent=initial.game_version||'';$('persistentLogPath').textContent=initial.log_path||'';const initialRadio=document.querySelector(`input[name="cdn"][value="${CSS.escape(INITIAL_CDN)}"]`);if(initialRadio)initialRadio.checked=true;if(HOST_PLATFORM==='darwin'){const description=$('directoryDescription');$('gameDir').dataset.i18nAttr='placeholder:launcher.directory.placeholder_mac';description.dataset.i18n='launcher.directory.description_mac';description.dataset.i18nCode='BrownDust II.app';await applyStatic()}await sync();if(AUTO_OPEN){await inspect();await saved();await navigateScene('desk')}}catch(error){await show(problemText(error),true)}finally{setBusy(false)}}
const updateNotes=notes=>!notes?'':typeof notes==='string'?notes:notes[locale]||notes.en_us||Object.values(notes).find(Boolean)||'';
function formatBytes(bytes){const mb=bytes>=1048576,value=bytes/(mb?1048576:1024);try{return new Intl.NumberFormat(HTML_LANG[locale],{style:'unit',unit:mb?'megabyte':'kilobyte',maximumFractionDigits:1}).format(value)}catch{return value.toFixed(1)+(mb?' MB':' KB')}}
function formatDate(value){const date=new Date(value+'T00:00:00Z');if(!/^\d{4}-\d{2}-\d{2}$/.test(value)||isNaN(date))return value;try{return date.toLocaleDateString(HTML_LANG[locale],{year:'numeric',month:'long',day:'numeric',timeZone:'UTC'})}catch{return value}}
diff --git a/go/internal/client/app/web/lang/en_us.json b/go/internal/client/app/web/lang/en_us.json
index 97a33ec..b5a6f63 100644
--- a/go/internal/client/app/web/lang/en_us.json
+++ b/go/internal/client/app/web/lang/en_us.json
@@ -1,30 +1,28 @@
{
"launcher.title": "BD2 Launcher",
- "launcher.top_note": "BD2 Launcher · Settings stay on this computer",
"launcher.language": "Language",
"launcher.window.controls": "Window controls",
"launcher.window.minimize": "Minimize",
"launcher.window.maximize": "Maximize or restore",
"launcher.window.close": "Close",
"launcher.browse": "Browse",
- "launcher.directory.heading": "Start with the\ngame directory.",
- "launcher.directory.lead": "Select the installed game folder.\nWe will check the game executable and asset files before setting up the connection.",
+ "launcher.directory.heading": "Choose where\nto install.",
+ "launcher.directory.lead": "No game installed? Choose a location, continue setup, then select Prepare client.\nYou can also select an existing game folder.",
"launcher.directory.label": "BrownDust II · Client setup",
- "launcher.directory.title": "Select game directory",
- "launcher.directory.description": "Select the folder that contains %[1]s.",
+ "launcher.directory.title": "Game installation location",
+ "launcher.directory.description": "Choose a new installation directory or an existing folder containing %[1]s.",
"launcher.directory.description_mac": "Select %[1]s or the folder that contains it.",
"launcher.directory.field": "Game installation directory",
"launcher.directory.placeholder": "Example: E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "Example: /Applications/BrownDust II.app",
- "launcher.directory.hint": "Enter a path directly or browse for a folder.",
+ "launcher.directory.hint": "Enter a new path or browse existing folders.",
"launcher.directory.inspect": "Check directory",
"launcher.directory.next": "Continue to server setup",
- "launcher.directory.note": "This step only checks files; it does not modify game assets.",
"launcher.directory.found": "Game executable and asset file found.",
"launcher.directory.incomplete": "Check complete; review the missing items in the launcher.",
"launcher.directory.changed": "The directory changed; check it again.",
"launcher.server.heading": "Next, set up\nthe server.",
- "launcher.server.lead": "Enter the address of the server to connect to.\nIn the launcher you can then choose a resource source, apply the patch, and install plugins.",
+ "launcher.server.lead": "Enter the server address you want to connect to.\nThen select Prepare client in the launcher to download and install the missing game.",
"launcher.server.label": "Directory selected · You can still change it later",
"launcher.server.title": "Server address",
"launcher.server.description": "Enter the full address; a port may be included.",
@@ -72,7 +70,7 @@
"launcher.resources.policy_server": "Resource URLs supplied by the server",
"launcher.save": "Save connection settings",
"launcher.unsaved": "Current settings have not been saved.",
- "launcher.prepare.title": "Patch and plugins",
+ "launcher.prepare.title": "Installation and preparation",
"launcher.prepare.note": "Close the game first. One-click prepare also downloads required game files and installs BepInEx from the launcher package. The patch only changes the built-in Intro address and keeps a %[1]s backup.",
"launcher.prepare.patch": "Apply client patch",
"launcher.prepare.install": "Install / update plugins",
@@ -188,5 +186,6 @@
"launcher.status.tagline": "LOCAL STATUS",
"launcher.resources.official.code": "OFFICIAL",
"launcher.resources.local.code": "LOCAL",
- "launcher.resources.server.code": "SERVER"
+ "launcher.resources.server.code": "SERVER",
+ "backend.directory_selected": "Installation location selected"
}
diff --git a/go/internal/client/app/web/lang/ja_jp.json b/go/internal/client/app/web/lang/ja_jp.json
index 1ad64e7..bc6ef42 100644
--- a/go/internal/client/app/web/lang/ja_jp.json
+++ b/go/internal/client/app/web/lang/ja_jp.json
@@ -1,30 +1,28 @@
{
"launcher.title": "BD2 ランチャー",
- "launcher.top_note": "BD2 ランチャー · 設定はこの PC に保存されます",
"launcher.language": "言語",
"launcher.window.controls": "ウィンドウ操作",
"launcher.window.minimize": "最小化",
"launcher.window.maximize": "最大化 / 元に戻す",
"launcher.window.close": "閉じる",
"launcher.browse": "参照",
- "launcher.directory.heading": "まずは\nフォルダー選択から。",
- "launcher.directory.lead": "インストール済みのゲームフォルダーを選択してください。\nゲーム本体とリソースファイルを確認してから、接続設定に進みます。",
+ "launcher.directory.heading": "まずはゲームの\nインストール先を。",
+ "launcher.directory.lead": "未インストールの場合は保存先を選び、設定後に一括準備を実行してください。\n既存のゲームフォルダーも選択できます。",
"launcher.directory.label": "BrownDust II · クライアント設定",
- "launcher.directory.title": "ゲームフォルダーを選択",
- "launcher.directory.description": "%[1]s があるフォルダーを選択してください。",
+ "launcher.directory.title": "ゲームのインストール先",
+ "launcher.directory.description": "新しいインストール先、または %[1]s を含む既存のフォルダーを選択してください。",
"launcher.directory.description_mac": "%[1]s またはそれがあるフォルダーを選択してください。",
"launcher.directory.field": "ゲームのインストール先",
"launcher.directory.placeholder": "例: E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "例: /Applications/BrownDust II.app",
- "launcher.directory.hint": "パスを直接入力するか、参照して選択できます。",
+ "launcher.directory.hint": "新しいパスの入力、または既存のフォルダーの選択ができます。",
"launcher.directory.inspect": "フォルダーを確認",
"launcher.directory.next": "サーバー設定へ進む",
- "launcher.directory.note": "この手順ではファイルを確認するだけで、ゲームのリソースは変更しません。",
"launcher.directory.found": "ゲーム本体とリソースファイルが見つかりました。",
"launcher.directory.incomplete": "確認が完了しました。不足している項目はランチャーで確認してください。",
"launcher.directory.changed": "フォルダーが変更されました。もう一度確認してください。",
"launcher.server.heading": "次に、\nサーバーを設定します。",
- "launcher.server.lead": "接続先のサーバーアドレスを入力してください。\nランチャーでは、リソースの取得元の選択、パッチの適用、プラグインのインストールができます。",
+ "launcher.server.lead": "接続するサーバーのアドレスを入力してください。\nその後、ランチャーの一括準備で未インストールのゲームをダウンロードできます。",
"launcher.server.label": "フォルダー選択済み · 後から変更できます",
"launcher.server.title": "サーバーアドレス",
"launcher.server.description": "完全なアドレスを入力してください。ポート番号も指定できます。",
@@ -72,7 +70,7 @@
"launcher.resources.policy_server": "リソースのアドレスはサーバーが提供します",
"launcher.save": "接続設定を保存",
"launcher.unsaved": "現在の設定はまだ保存されていません。",
- "launcher.prepare.title": "パッチとプラグイン",
+ "launcher.prepare.title": "インストールと準備",
"launcher.prepare.note": "操作の前にゲームを終了してください。まとめて準備は、必要なゲームファイルをダウンロードし、ランチャー同梱のパッケージから BepInEx をインストールします。パッチは内蔵の Intro アドレスのみを変更し、%[1]s のバックアップを残します。",
"launcher.prepare.patch": "クライアントパッチを適用",
"launcher.prepare.install": "プラグインをインストール / 更新",
@@ -188,5 +186,6 @@
"launcher.status.tagline": "ローカル状態",
"launcher.resources.official.code": "公式",
"launcher.resources.local.code": "ローカル",
- "launcher.resources.server.code": "サーバー"
+ "launcher.resources.server.code": "サーバー",
+ "backend.directory_selected": "インストール先を選択しました"
}
diff --git a/go/internal/client/app/web/lang/ko_kr.json b/go/internal/client/app/web/lang/ko_kr.json
index 4b05131..cd76b70 100644
--- a/go/internal/client/app/web/lang/ko_kr.json
+++ b/go/internal/client/app/web/lang/ko_kr.json
@@ -1,30 +1,28 @@
{
"launcher.title": "BD2 런처",
- "launcher.top_note": "BD2 런처 · 설정은 이 컴퓨터에 저장됩니다",
"launcher.language": "언어",
"launcher.window.controls": "창 제어",
"launcher.window.minimize": "최소화",
"launcher.window.maximize": "최대화 또는 이전 크기로 복원",
"launcher.window.close": "닫기",
"launcher.browse": "찾아보기",
- "launcher.directory.heading": "게임 폴더부터\n시작하세요.",
- "launcher.directory.lead": "설치된 게임 폴더를 선택하세요.\n게임 실행 파일과 리소스 파일을 확인한 뒤 연결 설정으로 넘어갑니다.",
+ "launcher.directory.heading": "게임을 설치할\n위치를 선택하세요.",
+ "launcher.directory.lead": "게임이 없나요? 설치 위치를 선택하고 설정을 마친 뒤 한 번에 준비를 실행하세요.\n이미 설치된 게임 폴더를 선택해도 됩니다.",
"launcher.directory.label": "BrownDust II · 클라이언트 설정",
- "launcher.directory.title": "게임 폴더 선택",
- "launcher.directory.description": "%[1]s 파일이 있는 폴더를 선택하세요.",
+ "launcher.directory.title": "게임 설치 위치",
+ "launcher.directory.description": "새 설치 경로 또는 %[1]s 파일이 있는 기존 게임 폴더를 선택하세요.",
"launcher.directory.description_mac": "%[1]s 또는 이 앱이 있는 폴더를 선택하세요.",
"launcher.directory.field": "게임 설치 폴더",
"launcher.directory.placeholder": "예: E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "예: /Applications/BrownDust II.app",
- "launcher.directory.hint": "경로를 직접 입력하거나 폴더를 찾아볼 수 있습니다.",
+ "launcher.directory.hint": "새 경로를 입력하거나 기존 폴더를 찾아볼 수 있습니다.",
"launcher.directory.inspect": "폴더 확인",
"launcher.directory.next": "서버 설정으로 계속",
- "launcher.directory.note": "이 단계에서는 파일만 확인하며 게임 리소스를 수정하지 않습니다.",
"launcher.directory.found": "게임 실행 파일과 리소스 파일을 찾았습니다.",
"launcher.directory.incomplete": "확인을 마쳤습니다. 누락된 항목은 런처에서 확인하세요.",
"launcher.directory.changed": "폴더가 변경되었습니다. 다시 확인하세요.",
"launcher.server.heading": "이제\n서버를 설정하세요.",
- "launcher.server.lead": "연결할 서버 주소를 입력하세요.\n런처에서 리소스 출처를 선택하고, 패치를 적용하고, 플러그인을 설치할 수 있습니다.",
+ "launcher.server.lead": "연결할 서버 주소를 입력하세요.\n이후 런처에서 한 번에 준비를 실행하면 없는 게임을 다운로드하고 설치합니다.",
"launcher.server.label": "폴더 선택 완료 · 나중에 변경할 수 있습니다",
"launcher.server.title": "서버 주소",
"launcher.server.description": "전체 주소를 입력하세요. 포트를 포함할 수 있습니다.",
@@ -72,7 +70,7 @@
"launcher.resources.policy_server": "서버가 리소스 주소를 제공합니다",
"launcher.save": "연결 설정 저장",
"launcher.unsaved": "현재 설정이 아직 저장되지 않았습니다.",
- "launcher.prepare.title": "패치 및 플러그인",
+ "launcher.prepare.title": "설치 및 준비",
"launcher.prepare.note": "작업 전에 게임을 종료하세요. 한 번에 준비는 필요한 게임 파일을 내려받고 런처 패키지에서 BepInEx를 설치합니다. 패치는 내장된 Intro 주소만 변경하며 %[1]s 백업을 남깁니다.",
"launcher.prepare.patch": "클라이언트 패치 적용",
"launcher.prepare.install": "플러그인 설치 / 업데이트",
@@ -188,5 +186,6 @@
"launcher.status.tagline": "로컬 상태",
"launcher.resources.official.code": "공식",
"launcher.resources.local.code": "로컬",
- "launcher.resources.server.code": "서버"
+ "launcher.resources.server.code": "서버",
+ "backend.directory_selected": "설치 위치를 선택했습니다"
}
diff --git a/go/internal/client/app/web/lang/zh_cn.json b/go/internal/client/app/web/lang/zh_cn.json
index 1c810c5..c48cf4b 100644
--- a/go/internal/client/app/web/lang/zh_cn.json
+++ b/go/internal/client/app/web/lang/zh_cn.json
@@ -1,30 +1,28 @@
{
"launcher.title": "BD2 启动器",
- "launcher.top_note": "BD2 启动器 · 配置保存在本机",
"launcher.language": "语言",
"launcher.window.controls": "窗口控制",
"launcher.window.minimize": "最小化",
"launcher.window.maximize": "最大化或还原",
"launcher.window.close": "关闭",
"launcher.browse": "浏览",
- "launcher.directory.heading": "先从游戏目录\n开始。",
- "launcher.directory.lead": "选择已安装的游戏文件夹。\n我们会检查游戏程序和资源文件,再继续设置连接。",
+ "launcher.directory.heading": "先选好游戏\n安装位置。",
+ "launcher.directory.lead": "还没安装?选择一个安装位置,继续设置后点击一键准备。\n已有游戏也可以直接选择原来的文件夹。",
"launcher.directory.label": "BrownDust II · 客户端配置",
- "launcher.directory.title": "选择游戏目录",
- "launcher.directory.description": "请选择包含 %[1]s 的文件夹。",
+ "launcher.directory.title": "游戏安装位置",
+ "launcher.directory.description": "选择新的安装目录,或包含 %[1]s 的已有游戏文件夹。",
"launcher.directory.description_mac": "请选择 %[1]s 或它所在的文件夹。",
"launcher.directory.field": "游戏安装目录",
"launcher.directory.placeholder": "例如 E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "例如 /Applications/BrownDust II.app",
- "launcher.directory.hint": "可直接填写路径,也可以浏览目录。",
+ "launcher.directory.hint": "可以填写新路径,也可以浏览已有目录。",
"launcher.directory.inspect": "检查目录",
"launcher.directory.next": "继续设置服务器",
- "launcher.directory.note": "此步骤只检查文件,不会修改游戏资源。",
"launcher.directory.found": "游戏程序和资源文件已检测到。",
"launcher.directory.incomplete": "检查已完成,请在启动器查看缺失项。",
"launcher.directory.changed": "目录已修改,请重新检查。",
"launcher.server.heading": "接下来,\n设置服务器。",
- "launcher.server.lead": "填写要连接的服务端地址。\n进入启动器后,你可以选择资源来源、应用补丁和安装插件。",
+ "launcher.server.lead": "填写要连接的服务端地址。\n进入启动器后,点击一键准备即可下载并安装缺失的游戏。",
"launcher.server.label": "目录已选择 · 之后仍可修改",
"launcher.server.title": "服务器地址",
"launcher.server.description": "填写完整地址,可以包含端口。",
@@ -72,7 +70,7 @@
"launcher.resources.policy_server": "由服务器提供资源地址",
"launcher.save": "保存连接设置",
"launcher.unsaved": "当前设置尚未保存。",
- "launcher.prepare.title": "补丁与插件",
+ "launcher.prepare.title": "安装与准备",
"launcher.prepare.note": "操作前请先关闭游戏。一键准备会按需下载游戏文件,并从启动器自带包安装 BepInEx。补丁只修改内置 Intro 地址,并保留 %[1]s 备份。",
"launcher.prepare.patch": "应用客户端补丁",
"launcher.prepare.install": "安装 / 更新插件",
@@ -188,5 +186,6 @@
"launcher.status.tagline": "本机状态",
"launcher.resources.official.code": "官方",
"launcher.resources.local.code": "本地",
- "launcher.resources.server.code": "服务器"
+ "launcher.resources.server.code": "服务器",
+ "backend.directory_selected": "已选择安装位置"
}
diff --git a/go/internal/client/app/web/lang/zh_tw.json b/go/internal/client/app/web/lang/zh_tw.json
index ab61e34..8055699 100644
--- a/go/internal/client/app/web/lang/zh_tw.json
+++ b/go/internal/client/app/web/lang/zh_tw.json
@@ -1,30 +1,28 @@
{
"launcher.title": "BD2 啟動器",
- "launcher.top_note": "BD2 啟動器 · 設定儲存在本機",
"launcher.language": "語言",
"launcher.window.controls": "視窗控制項",
"launcher.window.minimize": "最小化",
"launcher.window.maximize": "最大化或還原",
"launcher.window.close": "關閉",
"launcher.browse": "瀏覽",
- "launcher.directory.heading": "先從遊戲目錄\n開始。",
- "launcher.directory.lead": "選擇已安裝的遊戲資料夾。\n我們會先檢查遊戲程式和資源檔案,再繼續設定連線。",
+ "launcher.directory.heading": "先選好遊戲\n安裝位置。",
+ "launcher.directory.lead": "尚未安裝?選擇安裝位置,繼續設定後點擊一鍵準備。\n已有遊戲也可以直接選擇原來的資料夾。",
"launcher.directory.label": "BrownDust II · 用戶端設定",
- "launcher.directory.title": "選擇遊戲目錄",
- "launcher.directory.description": "請選擇包含 %[1]s 的資料夾。",
+ "launcher.directory.title": "遊戲安裝位置",
+ "launcher.directory.description": "選擇新的安裝目錄,或包含 %[1]s 的現有遊戲資料夾。",
"launcher.directory.description_mac": "請選擇 %[1]s 或其所在的資料夾。",
"launcher.directory.field": "遊戲安裝目錄",
"launcher.directory.placeholder": "例如 E:\\Games\\BrownDust II",
"launcher.directory.placeholder_mac": "例如 /Applications/BrownDust II.app",
- "launcher.directory.hint": "可直接輸入路徑,也可以瀏覽資料夾。",
+ "launcher.directory.hint": "可以填寫新路徑,也可以瀏覽現有目錄。",
"launcher.directory.inspect": "檢查目錄",
"launcher.directory.next": "繼續設定伺服器",
- "launcher.directory.note": "此步驟只會檢查檔案,不會修改遊戲資源。",
"launcher.directory.found": "已偵測到遊戲程式和資源檔案。",
"launcher.directory.incomplete": "檢查完成,請在啟動器中查看缺少的項目。",
"launcher.directory.changed": "目錄已變更,請重新檢查。",
"launcher.server.heading": "接下來,\n設定伺服器。",
- "launcher.server.lead": "輸入要連線的伺服器位址。\n進入啟動器後,即可選擇資源來源、套用修補程式並安裝插件。",
+ "launcher.server.lead": "填寫要連線的伺服器位址。\n進入啟動器後,點擊一鍵準備即可下載並安裝缺少的遊戲。",
"launcher.server.label": "已選擇目錄 · 之後仍可修改",
"launcher.server.title": "伺服器位址",
"launcher.server.description": "請輸入完整位址,可包含連接埠。",
@@ -72,7 +70,7 @@
"launcher.resources.policy_server": "由伺服器提供資源位址",
"launcher.save": "儲存連線設定",
"launcher.unsaved": "目前的設定尚未儲存。",
- "launcher.prepare.title": "修補程式與插件",
+ "launcher.prepare.title": "安裝與準備",
"launcher.prepare.note": "操作前請先關閉遊戲。一鍵準備會視需要下載遊戲檔案,並從啟動器內建包安裝 BepInEx。修補程式只會修改內建的 Intro 位址,並保留 %[1]s 備份。",
"launcher.prepare.patch": "套用用戶端修補程式",
"launcher.prepare.install": "安裝 / 更新插件",
@@ -188,5 +186,6 @@
"launcher.status.tagline": "本機狀態",
"launcher.resources.official.code": "官方",
"launcher.resources.local.code": "本機",
- "launcher.resources.server.code": "伺服器"
+ "launcher.resources.server.code": "伺服器",
+ "backend.directory_selected": "已選擇安裝位置"
}
diff --git a/go/internal/client/config/config.go b/go/internal/client/config/config.go
index 74d327e..d3ccbb7 100644
--- a/go/internal/client/config/config.go
+++ b/go/internal/client/config/config.go
@@ -8,6 +8,7 @@ import (
"net"
"net/url"
"path/filepath"
+ "reflect"
"strconv"
"strings"
@@ -158,6 +159,9 @@ func Save(gameDir string, in Settings) (Settings, error) {
if err != nil {
return Settings{}, err
}
+ if current, err := Load(gameDir); err == nil && reflect.DeepEqual(current, settings) {
+ return settings, nil
+ }
path := Path(gameDir)
if err := commonconfig.Save(path, settings, commonconfig.WriteOptions{}); err != nil {
return Settings{}, fmt.Errorf("client config: save: %w", err)
diff --git a/go/internal/client/config/preferences.go b/go/internal/client/config/preferences.go
index 4d8e802..b3bb922 100644
--- a/go/internal/client/config/preferences.go
+++ b/go/internal/client/config/preferences.go
@@ -54,6 +54,9 @@ func SavePreferences(gameDirectory string) error {
return err
}
preferences := Preferences{SchemaVersion: preferencesSchemaVersion, GameDirectory: abs}
+ if current, err := LoadPreferences(); err == nil && current == preferences {
+ return nil
+ }
if err := commonconfig.Save(path, preferences, commonconfig.WriteOptions{DirectoryMode: 0o700}); err != nil {
return fmt.Errorf("save client preferences: %w", err)
}
diff --git a/go/internal/client/download/archive.go b/go/internal/client/download/archive.go
index e2641db..a9a93b3 100644
--- a/go/internal/client/download/archive.go
+++ b/go/internal/client/download/archive.go
@@ -6,7 +6,6 @@ import (
"encoding/binary"
"errors"
"fmt"
- "hash/crc32"
"io"
"os"
"path/filepath"
@@ -192,43 +191,14 @@ func extractArchive(path, root string, game bool, digest string) error {
return err
}
}
- marker := filepath.Join(root, ".bd2-official-game-version")
if game {
- value, err := os.ReadFile(marker)
- ready := err == nil && strings.TrimSpace(string(value)) == digest
- for _, entry := range entries {
- info, err := os.Stat(entry.target)
- if err != nil || info.IsDir() != entry.file.FileInfo().IsDir() || (!info.IsDir() && uint64(info.Size()) != entry.file.UncompressedSize64) {
- ready = false
- break
- }
- if !info.IsDir() {
- installed, err := os.Open(entry.target)
- if err != nil {
- ready = false
- break
- }
- hash := crc32.NewIEEE()
- _, readErr := io.Copy(hash, installed)
- closeErr := installed.Close()
- if readErr != nil || closeErr != nil || hash.Sum32() != entry.file.CRC32 {
- ready = false
- break
- }
- }
- }
- if ready {
- return nil
- }
+ return extractGame(entries, root, digest)
}
for _, entry := range entries {
if err := extractEntry(entry); err != nil {
return fmt.Errorf("extract %s: %w", entry.file.Name, err)
}
}
- if game {
- return atomicWrite(marker, []byte(digest+"\n"))
- }
return nil
}
diff --git a/go/internal/client/download/client.go b/go/internal/client/download/client.go
index 9f3b255..1ef0b20 100644
--- a/go/internal/client/download/client.go
+++ b/go/internal/client/download/client.go
@@ -89,31 +89,36 @@ func Client(ctx context.Context, options Options, out io.Writer) (Installation,
return result, err
}
defer d.client.CloseIdleConnections()
- builds, err := d.fastest(ctx, m.BuildOrigins, m.GamePath, "Game ZIP")
- if err != nil {
- return result, err
- }
dataPath := "/GameData/" + m.GameDataVersion
serverPath := "/ServerData/" + m.Platform + "/HD/" + m.BundleVersion
- dataOrigins, err := d.fastest(ctx, m.ResourceOrigins, dataPath+"/release/common-dbdata.bin", "GameData")
- if err != nil {
- return result, err
- }
- bundleOrigins, err := d.fastest(ctx, m.ResourceOrigins, serverPath+"/catalog_alpha.json", "ServerData")
- if err != nil {
- return result, err
- }
if options.ProbeOnly {
+ for _, probe := range []struct {
+ origins []string
+ path, label string
+ }{{m.BuildOrigins, m.GamePath, "Game ZIP"}, {m.ResourceOrigins, dataPath + "/release/common-dbdata.bin", "GameData"}, {m.ResourceOrigins, serverPath + "/catalog_alpha.json", "ServerData"}} {
+ if _, err := d.fastest(ctx, probe.origins, probe.path, probe.label); err != nil {
+ return result, err
+ }
+ }
return result, nil
}
+ d.measureOrigins = true
archive := filepath.Join(packageDir, "downloads", "BrownDust-II-"+m.GameVersion+".zip")
- if err := d.receiveAll(ctx, []file{{remote: m.GamePath, target: archive, digest: m.GameSHA256, size: m.GameBytes}}, builds, 1); err != nil {
+ gameFile := file{remote: m.GamePath, target: archive, digest: m.GameSHA256, size: m.GameBytes}
+ builds := m.BuildOrigins
+ if !d.verified(gameFile) {
+ builds, err = d.fastest(ctx, m.BuildOrigins, m.GamePath, "Game ZIP")
+ if err != nil {
+ return result, err
+ }
+ }
+ if err := d.receiveAll(ctx, []file{gameFile}, builds, 1); err != nil {
return result, err
}
if err := extractArchive(archive, result.GameDir, true, m.GameSHA256); err != nil {
return result, err
}
- if err := d.resources(ctx, result.ResourceDir, m, serverPath, dataPath, bundleOrigins, dataOrigins, options.Workers); err != nil {
+ if err := d.resources(ctx, result.ResourceDir, m, serverPath, dataPath, m.ResourceOrigins, m.ResourceOrigins, options.Workers); err != nil {
return result, err
}
d.log("Downloaded: game=%s resources=%s", result.GameDir, result.ResourceDir)
diff --git a/go/internal/client/download/client_test.go b/go/internal/client/download/client_test.go
index 8176720..a703e67 100644
--- a/go/internal/client/download/client_test.go
+++ b/go/internal/client/download/client_test.go
@@ -11,8 +11,11 @@ import (
"net/http/httptest"
"os"
"path/filepath"
+ "slices"
"strings"
+ "sync"
"testing"
+ "time"
commonconfig "bd2server/internal/common/config"
)
@@ -38,10 +41,17 @@ func TestClientProbeAndDownloadOnlyDoNotRequirePreparationPackage(t *testing.T)
}
return raw.Bytes()
}
- game := makeArchive(requiredGameFiles)
+ gameNames := append(slices.Clone(requiredGameFiles), "BrownDust II_Data/resources.assets", "BrownDust II_Data/StreamingAssets/aa/catalog.json")
+ game := makeArchive(gameNames)
data := makeArchive([]string{"common.db"})
catalog := []byte(`{"m_InternalIds":["{BDNetwork.CdnInfo.Info}/StandaloneWindows64/HD/` + bundleVersion + `/scene.bundle"]}` + strings.Repeat(" ", 256<<10))
+ bundleData := []byte{'U', 'n', 'i', 't', 'y', 'F', 'S', 0, 0, 0, 0, 6, 'v', 0, 'r', 0, 0, 0, 0, 0, 0, 0, 0, 28, 'd', 'a', 't', 'a'}
+ var mu sync.Mutex
+ var requested []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ requested = append(requested, r.URL.Path)
+ mu.Unlock()
switch {
case strings.HasPrefix(r.URL.Path, "/Build/"):
_, _ = w.Write(game)
@@ -56,7 +66,7 @@ func TestClientProbeAndDownloadOnlyDoNotRequirePreparationPackage(t *testing.T)
case strings.HasSuffix(r.URL.Path, "/catalog_alpha.hash"):
_, _ = io.WriteString(w, "0f90a94601be05737f86a4ec7a1c889f")
case strings.HasSuffix(r.URL.Path, "/scene.bundle"):
- _, _ = w.Write([]byte{'U', 'n', 'i', 't', 'y', 'F', 'S', 0, 0, 0, 0, 6, 'v', 0, 'r', 0, 0, 0, 0, 0, 0, 0, 0, 24})
+ _, _ = w.Write(bundleData)
default:
http.NotFound(w, r)
}
@@ -106,4 +116,151 @@ func TestClientProbeAndDownloadOnlyDoNotRequirePreparationPackage(t *testing.T)
if _, err := os.Stat(filepath.Join(installed.ResourceDir, "resource-fetch-manifest.json")); err != nil {
t.Fatal("resource installation did not complete", err)
}
+ resetRequests := func() { mu.Lock(); requested = nil; mu.Unlock() }
+ requests := func() []string { mu.Lock(); defer mu.Unlock(); return slices.Clone(requested) }
+ run := func() {
+ t.Helper()
+ if _, err := Client(context.Background(), Options{PackageDir: root, Workers: 2}, io.Discard); err != nil {
+ t.Fatal(err)
+ }
+ }
+ snapshot := func() map[string]time.Time {
+ t.Helper()
+ out := map[string]time.Time{}
+ if err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if entry.IsDir() {
+ return nil
+ }
+ info, err := entry.Info()
+ if err == nil {
+ out[path] = info.ModTime()
+ }
+ return err
+ }); err != nil {
+ t.Fatal(err)
+ }
+ return out
+ }
+ assertUnchanged := func(before map[string]time.Time, except ...string) {
+ t.Helper()
+ after := snapshot()
+ if len(before) != len(after) {
+ t.Fatal("repeat changed the installation file set")
+ }
+ for path, stamp := range before {
+ if !slices.Contains(except, path) && after[path] != stamp {
+ t.Fatalf("repeat rewrote %s", path)
+ }
+ }
+ }
+ before := snapshot()
+ resetRequests()
+ run()
+ if got := requests(); len(got) != 0 {
+ t.Fatalf("complete installation still contacted download origins: %v", got)
+ }
+ assertUnchanged(before)
+ prepared := []string{"BrownDust II_Data/resources.assets", "BrownDust II_Data/StreamingAssets/aa/catalog.json"}
+ patched := []byte("launcher-prepared-content")
+ for _, relative := range prepared {
+ if err := os.WriteFile(filepath.Join(installed.GameDir, filepath.FromSlash(relative)), patched, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := RecordPreparedGame(installed.GameDir, prepared...); err != nil {
+ t.Fatal(err)
+ }
+ if err := RecordPreparedGame(installed.GameDir, "UnityPlayer.dll"); err == nil {
+ t.Fatal("unrecognized game change was accepted as launcher output")
+ }
+ before = snapshot()
+ resetRequests()
+ run()
+ if got := requests(); len(got) != 0 {
+ t.Fatalf("registered launcher output forced an official download: %v", got)
+ }
+ assertUnchanged(before)
+ player := filepath.Join(installed.GameDir, "UnityPlayer.dll")
+ bundle := filepath.Join(installed.ResourceDir, "ServerData", "StandaloneWindows64", "HD", bundleVersion, "scene.bundle")
+ for _, path := range []string{player, bundle} {
+ if err := os.Remove(path); err != nil {
+ t.Fatal(err)
+ }
+ }
+ resetRequests()
+ run()
+ got := requests()
+ if len(got) == 0 {
+ t.Fatal("missing resource was not downloaded")
+ }
+ for _, path := range got {
+ if !strings.HasSuffix(path, "/scene.bundle") {
+ t.Fatalf("repair fetched an already complete file: %s", path)
+ }
+ }
+ if actual, err := os.ReadFile(player); err != nil || !bytes.Equal(actual, bytes.Repeat([]byte("archive-payload"), 32<<10)) {
+ t.Fatal("missing game file was not repaired from cached official archive")
+ }
+ for _, relative := range prepared {
+ if actual, err := os.ReadFile(filepath.Join(installed.GameDir, filepath.FromSlash(relative))); err != nil || !bytes.Equal(actual, patched) {
+ t.Fatal("single-file repair overwrote registered launcher output")
+ }
+ }
+ for _, path := range []string{player, bundle} {
+ body, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body[len(body)-1] ^= 1
+ if err := os.WriteFile(path, body, 0600); err != nil {
+ t.Fatal(err)
+ }
+ stamp := time.Now().Add(2 * time.Second)
+ if err := os.Chtimes(path, stamp, stamp); err != nil {
+ t.Fatal(err)
+ }
+ }
+ resetRequests()
+ run()
+ got = requests()
+ if len(got) == 0 {
+ t.Fatal("same-size damaged resource was trusted")
+ }
+ for _, path := range got {
+ if !strings.HasSuffix(path, "/scene.bundle") {
+ t.Fatalf("damaged-file repair fetched unaffected content: %s", path)
+ }
+ }
+ if actual, err := os.ReadFile(player); err != nil || !bytes.Equal(actual, bytes.Repeat([]byte("archive-payload"), 32<<10)) {
+ t.Fatal("same-size game corruption survived cached installation receipt")
+ }
+ if actual, err := os.ReadFile(bundle); err != nil || !bytes.Equal(actual, bundleData) {
+ t.Fatal("same-size bundle payload corruption survived its valid header")
+ }
+ unknown := filepath.Join(installed.GameDir, filepath.FromSlash(prepared[0]))
+ if err := os.WriteFile(unknown, []byte("unregistered modification"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ resetRequests()
+ run()
+ if actual, err := os.ReadFile(unknown); err != nil || !bytes.Equal(actual, bytes.Repeat([]byte("archive-payload"), 32<<10)) {
+ t.Fatal("unregistered launcher-file change was silently trusted")
+ }
+ if got := requests(); len(got) != 0 {
+ t.Fatalf("game-file repair unnecessarily contacted the network: %v", got)
+ }
+ catalogTarget := filepath.Join(installed.GameDir, filepath.FromSlash(prepared[1]))
+ if err := os.WriteFile(catalogTarget, []byte("unregistered catalog change"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := RecordPreparedGame(installed.GameDir, prepared[0]); err != nil {
+ t.Fatal(err)
+ }
+ run()
+ if actual, err := os.ReadFile(catalogTarget); err != nil || !bytes.Equal(actual, bytes.Repeat([]byte("archive-payload"), 32<<10)) {
+ t.Fatal("registering one prepared file also trusted another modified file")
+ }
}
diff --git a/go/internal/client/download/game_receipt.go b/go/internal/client/download/game_receipt.go
new file mode 100644
index 0000000..fbc5853
--- /dev/null
+++ b/go/internal/client/download/game_receipt.go
@@ -0,0 +1,186 @@
+package download
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "os"
+ "path/filepath"
+ "slices"
+
+ commonconfig "bd2server/internal/common/config"
+)
+
+const gameReceiptName = ".bd2-game-install.json"
+
+type installedFile struct {
+ SourceBytes uint64 `json:"source_bytes"`
+ SourceCRC32 uint32 `json:"source_crc32"`
+ Verified receipt `json:"verified"`
+}
+type gameInstallation struct {
+ SchemaVersion int `json:"schema_version"`
+ ArchiveSHA256 string `json:"archive_sha256"`
+ Files map[string]installedFile `json:"files"`
+}
+
+func readInstallation(root string) (gameInstallation, error) {
+ return commonconfig.Load(filepath.Join(root, gameReceiptName), gameInstallation{}, commonconfig.DecodeOptions{DisallowUnknownFields: true, RejectTrailing: true, RejectNull: true})
+}
+
+func fileHashes(path string) (receipt, uint32, error) {
+ in, err := os.Open(path)
+ if err != nil {
+ return receipt{}, 0, err
+ }
+ defer func() { _ = in.Close() }()
+ info, err := in.Stat()
+ if err != nil {
+ return receipt{}, 0, err
+ }
+ if !info.Mode().IsRegular() {
+ return receipt{}, 0, errors.New("installed game file is not regular")
+ }
+ sha, crc := sha256.New(), crc32.NewIEEE()
+ n, err := io.Copy(io.MultiWriter(sha, crc), in)
+ if err != nil {
+ return receipt{}, 0, err
+ }
+ after, err := os.Stat(path)
+ if err != nil {
+ return receipt{}, 0, err
+ }
+ if n != info.Size() || after.Size() != info.Size() || after.ModTime() != info.ModTime() {
+ return receipt{}, 0, errors.New("installed game file changed during verification")
+ }
+ return receipt{Bytes: n, Modified: after.ModTime().UnixNano(), SHA256: hex.EncodeToString(sha.Sum(nil))}, crc.Sum32(), nil
+}
+
+func installedMatches(entry archiveEntry, previous installedFile) (installedFile, bool, error) {
+ info, err := os.Stat(entry.target)
+ if errors.Is(err, os.ErrNotExist) {
+ return installedFile{}, false, nil
+ }
+ if err != nil {
+ return installedFile{}, false, err
+ }
+ if !info.Mode().IsRegular() {
+ return installedFile{}, false, fmt.Errorf("installed game output is not a regular file: %s", entry.target)
+ }
+ bound := previous.SourceBytes == entry.file.UncompressedSize64 && previous.SourceCRC32 == entry.file.CRC32 && sha256Pattern.MatchString(previous.Verified.SHA256)
+ if bound && previous.Verified.Bytes == info.Size() && previous.Verified.Modified == info.ModTime().UnixNano() {
+ return previous, true, nil
+ }
+ verified, crc, err := fileHashes(entry.target)
+ if err != nil {
+ return installedFile{}, false, err
+ }
+ if bound && verified.SHA256 == previous.Verified.SHA256 || uint64(verified.Bytes) == entry.file.UncompressedSize64 && crc == entry.file.CRC32 {
+ return installedFile{SourceBytes: entry.file.UncompressedSize64, SourceCRC32: entry.file.CRC32, Verified: verified}, true, nil
+ }
+ return installedFile{}, false, nil
+}
+
+func extractGame(entries []archiveEntry, root, digest string) error {
+ previous, err := readInstallation(root)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ if previous.SchemaVersion != 1 || previous.ArchiveSHA256 != digest {
+ previous = gameInstallation{}
+ }
+ next := gameInstallation{SchemaVersion: 1, ArchiveSHA256: digest, Files: map[string]installedFile{}}
+ changed := previous.Files == nil
+ for _, entry := range entries {
+ if entry.file.FileInfo().IsDir() {
+ if err := os.MkdirAll(entry.target, 0755); err != nil {
+ return err
+ }
+ continue
+ }
+ relative, err := filepath.Rel(root, entry.target)
+ if err != nil {
+ return err
+ }
+ relative = filepath.ToSlash(relative)
+ verified, ready, err := installedMatches(entry, previous.Files[relative])
+ if err != nil {
+ return err
+ }
+ if !ready {
+ if err := extractEntry(entry); err != nil {
+ return fmt.Errorf("extract %s: %w", entry.file.Name, err)
+ }
+ verified, ready, err = installedMatches(entry, installedFile{})
+ if err != nil {
+ return err
+ }
+ if !ready {
+ return fmt.Errorf("extracted game file failed verification: %s", relative)
+ }
+ }
+ next.Files[relative] = verified
+ if previous.Files[relative] != verified {
+ changed = true
+ }
+ }
+ if len(previous.Files) != len(next.Files) {
+ changed = true
+ }
+ if !changed {
+ return nil
+ }
+ return commonconfig.Save(filepath.Join(root, gameReceiptName), next, commonconfig.WriteOptions{FileMode: 0644})
+}
+
+func RecordPreparedGame(gameDir string, relativePaths ...string) error {
+ for _, relative := range relativePaths {
+ if !slices.Contains([]string{"BrownDust II_Data/resources.assets", "BrownDust II_Data/StreamingAssets/aa/catalog.json"}, relative) {
+ return fmt.Errorf("cannot register unrecognized prepared game file: %s", relative)
+ }
+ }
+ record, err := readInstallation(gameDir)
+ if errors.Is(err, os.ErrNotExist) {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ if record.SchemaVersion != 1 || record.Files == nil {
+ return errors.New("unsupported game installation receipt")
+ }
+ changed := false
+ for _, relative := range relativePaths {
+ entry, ok := record.Files[relative]
+ if !ok {
+ return fmt.Errorf("prepared game file is absent from official archive: %s", relative)
+ }
+ path, err := safeTarget(gameDir, relative)
+ if err != nil {
+ return err
+ }
+ info, err := os.Stat(path)
+ if err != nil {
+ return err
+ }
+ if !info.Mode().IsRegular() {
+ return fmt.Errorf("prepared game output is not regular: %s", relative)
+ }
+ if info.Size() == entry.Verified.Bytes && info.ModTime().UnixNano() == entry.Verified.Modified {
+ continue
+ }
+ entry.Verified, _, err = fileHashes(path)
+ if err != nil {
+ return err
+ }
+ record.Files[relative] = entry
+ changed = true
+ }
+ if !changed {
+ return nil
+ }
+ return commonconfig.Save(filepath.Join(gameDir, gameReceiptName), record, commonconfig.WriteOptions{FileMode: 0644})
+}
diff --git a/go/internal/client/download/resources.go b/go/internal/client/download/resources.go
index bb40470..310f82d 100644
--- a/go/internal/client/download/resources.go
+++ b/go/internal/client/download/resources.go
@@ -12,7 +12,6 @@ import (
"strconv"
"strings"
- commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/release"
"bd2server/internal/common/resourcecatalog"
)
@@ -23,6 +22,7 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
for _, pin := range m.ResourceFiles {
pins[pin.Path] = pin
}
+ serverRanked, dataRanked := false, false
receive := func(files []file, origins []string, workers int) error {
if len(pins) != 0 {
for i := range files {
@@ -38,7 +38,39 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
usedPins[pin.Path] = true
}
}
- return d.receiveAll(ctx, files, origins, workers)
+ var missing []file
+ for _, item := range files {
+ if !d.verified(item) {
+ missing = append(missing, item)
+ }
+ }
+ if len(missing) == 0 {
+ return d.saveRecords()
+ }
+ if d.measureOrigins {
+ if strings.HasPrefix(missing[0].remote, dataPath+"/") {
+ if !dataRanked {
+ var err error
+ dataOrigins, err = d.fastest(ctx, origins, missing[0].remote, "GameData")
+ if err != nil {
+ return err
+ }
+ dataRanked = true
+ }
+ origins = dataOrigins
+ } else {
+ if !serverRanked {
+ var err error
+ serverOrigins, err = d.fastest(ctx, origins, missing[0].remote, "ServerData")
+ if err != nil {
+ return err
+ }
+ serverRanked = true
+ }
+ origins = serverOrigins
+ }
+ }
+ return d.receiveAll(ctx, missing, origins, workers)
}
serverDir := filepath.Join(root, "ServerData", m.Platform, "HD", m.BundleVersion)
dataDir := filepath.Join(root, "GameData", m.GameDataVersion)
@@ -107,7 +139,7 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
if size != stat.Size() {
return errors.New("GameData size metadata mismatch")
}
- entries, err := validateDataArchive(filepath.Join(dataDir, "release", "common-dbdata.bin"))
+ entries, err := d.dataArchiveEntries(filepath.Join(dataDir, "release", "common-dbdata.bin"))
if err != nil {
return err
}
@@ -144,9 +176,48 @@ func (d *downloader) resources(ctx context.Context, root string, m manifest, ser
}
total += info.Size()
}
- return commonconfig.Save(filepath.Join(root, "resource-fetch-manifest.json"), map[string]any{
+ metadata := map[string]any{
"bundle_version": m.BundleVersion, "game_data_version": m.GameDataVersion, "platform": m.Platform,
"server_data": map[string]any{"catalog_hash": strings.ToLower(actualHash), "bundles": len(files), "bytes": total},
"game_data": map[string]any{"version": m.GameDataVersion, "entry_count": entries, "bytes": size},
- }, commonconfig.WriteOptions{FileMode: 0644})
+ }
+ raw, err = json.MarshalIndent(metadata, "", " ")
+ if err != nil {
+ return err
+ }
+ raw = append(raw, '\n')
+ path := filepath.Join(root, "resource-fetch-manifest.json")
+ if current, err := os.ReadFile(path); err == nil && bytes.Equal(current, raw) {
+ return nil
+ } else if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ return atomicWrite(path, raw)
+}
+
+func (d *downloader) dataArchiveEntries(path string) (int, error) {
+ d.mu.Lock()
+ r := d.records[d.receiptKey(path)]
+ d.mu.Unlock()
+ info, err := os.Stat(path)
+ if err != nil {
+ return 0, err
+ }
+ if r.Bytes == info.Size() && r.Modified == info.ModTime().UnixNano() && r.ArchiveEntries > 0 {
+ return r.ArchiveEntries, nil
+ }
+ entries, err := validateDataArchive(path)
+ if err != nil {
+ return 0, err
+ }
+ after, err := os.Stat(path)
+ if err != nil {
+ return 0, err
+ }
+ if after.Size() != info.Size() || after.ModTime() != info.ModTime() {
+ return 0, errors.New("GameData changed during archive validation")
+ }
+ r.ArchiveEntries = entries
+ d.remember(path, r)
+ return entries, d.saveRecords()
}
diff --git a/go/internal/client/download/transfer.go b/go/internal/client/download/transfer.go
index 51aa809..e9c64b3 100644
--- a/go/internal/client/download/transfer.go
+++ b/go/internal/client/download/transfer.go
@@ -1,6 +1,7 @@
package download
import (
+ "bd2server/internal/common/util"
"context"
"crypto/sha256"
"encoding/hex"
@@ -26,8 +27,10 @@ type file struct {
}
type receipt struct {
- Bytes int64 `json:"bytes"`
- SHA256 string `json:"sha256"`
+ Bytes int64 `json:"bytes"`
+ Modified int64 `json:"modified"`
+ SHA256 string `json:"sha256"`
+ ArchiveEntries int `json:"archive_entries,omitempty"`
}
type downloader struct {
@@ -36,6 +39,8 @@ type downloader struct {
out io.Writer
mu sync.Mutex
records map[string]receipt
+ dirty bool
+ measureOrigins bool
}
func newDownloader(root string, out io.Writer) (*downloader, error) {
@@ -52,10 +57,7 @@ func newDownloader(root string, out io.Writer) (*downloader, error) {
return nil, err
}
if err == nil {
- if saved.SchemaVersion != 1 {
- return nil, errors.New("unsupported download checkpoint")
- }
- if saved.Files != nil {
+ if saved.SchemaVersion == 2 && saved.Files != nil {
d.records = saved.Files
}
}
@@ -68,27 +70,11 @@ func (d *downloader) log(format string, args ...any) {
_, _ = fmt.Fprintf(d.out, format+"\n", args...)
}
-func hashFile(path string) (string, error) {
- f, err := os.Open(path)
- if err != nil {
- return "", err
- }
- defer func() { _ = f.Close() }()
- h := sha256.New()
- if _, err = io.Copy(h, f); err != nil {
- return "", err
- }
- return hex.EncodeToString(h.Sum(nil)), nil
-}
-
func (d *downloader) verified(item file) bool {
info, err := os.Stat(item.target)
if err != nil || !info.Mode().IsRegular() || info.Size() == 0 || (item.size > 0 && item.size != info.Size()) {
return false
}
- if item.bundle && !validBundle(item.target, info.Size()) {
- return false
- }
key := d.receiptKey(item.target)
d.mu.Lock()
previous := d.records[key]
@@ -100,8 +86,52 @@ func (d *downloader) verified(item file) bool {
if expected == "" {
return false
}
- actual, err := hashFile(item.target)
- return err == nil && actual == expected
+ if previous.Bytes == info.Size() && previous.Modified == info.ModTime().UnixNano() && previous.SHA256 == expected {
+ return true
+ }
+ if item.bundle && !validBundle(item.target, info.Size()) {
+ return false
+ }
+ actual, err := util.SHA256File(item.target)
+ if err != nil || actual != expected {
+ return false
+ }
+ after, err := os.Stat(item.target)
+ if err != nil || after.Size() != info.Size() || after.ModTime() != info.ModTime() {
+ return false
+ }
+ entries := 0
+ if actual == previous.SHA256 {
+ entries = previous.ArchiveEntries
+ }
+ d.remember(item.target, receipt{Bytes: info.Size(), Modified: info.ModTime().UnixNano(), SHA256: actual, ArchiveEntries: entries})
+ return true
+}
+
+func (d *downloader) remember(target string, r receipt) {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ key := d.receiptKey(target)
+ if d.records[key] != r {
+ d.records[key] = r
+ d.dirty = true
+ }
+}
+
+func (d *downloader) saveRecords() error {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ if !d.dirty {
+ return nil
+ }
+ err := commonconfig.Save(d.checkpoint, struct {
+ SchemaVersion int `json:"schema_version"`
+ Files map[string]receipt `json:"files"`
+ }{2, d.records}, commonconfig.WriteOptions{FileMode: 0644})
+ if err == nil {
+ d.dirty = false
+ }
+ return err
}
func (d *downloader) receive(ctx context.Context, item file, origins []string) error {
@@ -171,14 +201,12 @@ func (d *downloader) receiveOnce(ctx context.Context, item file, origin string)
if err := os.Rename(temporary.Name(), item.target); err != nil {
return err
}
- key := d.receiptKey(item.target)
- d.mu.Lock()
- defer d.mu.Unlock()
- d.records[key] = receipt{Bytes: written, SHA256: actual}
- return commonconfig.Save(d.checkpoint, struct {
- SchemaVersion int `json:"schema_version"`
- Files map[string]receipt `json:"files"`
- }{1, d.records}, commonconfig.WriteOptions{FileMode: 0644})
+ info, err := os.Stat(item.target)
+ if err != nil {
+ return err
+ }
+ d.remember(item.target, receipt{Bytes: written, Modified: info.ModTime().UnixNano(), SHA256: actual})
+ return nil
}
func (d *downloader) receiptKey(target string) string {
@@ -223,10 +251,7 @@ feed:
}
close(jobs)
wg.Wait()
- if first != nil {
- return first
- }
- return ctx.Err()
+ return errors.Join(first, ctx.Err(), d.saveRecords())
}
func (d *downloader) fastest(ctx context.Context, origins []string, relative, label string) ([]string, error) {
@@ -260,7 +285,7 @@ func (d *downloader) fastest(ctx context.Context, origins []string, relative, la
}
n, err := io.Copy(io.Discard, io.LimitReader(response.Body, 4<<20))
speed := float64(0)
- if n >= 256<<10 {
+ if n > 0 {
speed = float64(n) / time.Since(start).Seconds()
}
results[i] = result{origin: origin, speed: speed, err: err}
diff --git a/go/internal/client/plugin/build_cache.go b/go/internal/client/plugin/build_cache.go
index 250f3ed..6d8fe6b 100644
--- a/go/internal/client/plugin/build_cache.go
+++ b/go/internal/client/plugin/build_cache.go
@@ -1,20 +1,18 @@
package plugin
import (
+ "bd2server/internal/common/util"
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
- "io"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
-
- commonconfig "bd2server/internal/common/config"
)
type buildManifest struct {
@@ -44,7 +42,7 @@ func (cache fileDigestCache) digest(path string) (string, error) {
return "", err
}
if info.Size() < 1024*1024 {
- return fileDigest(path)
+ return util.SHA256File(path)
}
stamp, reliable := fileChangeStamp(path, info)
if reliable {
@@ -52,7 +50,7 @@ func (cache fileDigestCache) digest(path string) (string, error) {
return previous.Hash, nil
}
}
- sum, err := fileDigest(path)
+ sum, err := util.SHA256File(path)
if err == nil && reliable {
cache[path] = cachedFileDigest{Stamp: stamp, Hash: sum}
}
@@ -108,7 +106,7 @@ func projectFingerprint(root string, inputs map[string]string, project, versionS
}
relevant[file] = sum
}
- sum, err := fileDigest(versionSource)
+ sum, err := util.SHA256File(versionSource)
if err != nil {
return "", err
}
@@ -210,19 +208,6 @@ func writeBuildInput(path, fingerprint string) error {
return os.WriteFile(path, content, 0o644)
}
-func fileDigest(path string) (string, error) {
- file, err := os.Open(path)
- if err != nil {
- return "", err
- }
- defer func() { _ = file.Close() }()
- hash := sha256.New()
- if _, err := io.Copy(hash, file); err != nil {
- return "", err
- }
- return hex.EncodeToString(hash.Sum(nil)), nil
-}
-
func currentBuild(path, fingerprint string, cache fileDigestCache) bool {
raw, err := os.ReadFile(path)
if err != nil {
@@ -262,5 +247,5 @@ func saveBuildJSON(path string, raw []byte) error {
if err := temporary.Close(); err != nil {
return err
}
- return commonconfig.ReplaceFile(temporary.Name(), path)
+ return util.ReplaceFile(temporary.Name(), path)
}
diff --git a/go/internal/client/plugin/build_test.go b/go/internal/client/plugin/build_test.go
index 0aa02a2..aeb0aef 100644
--- a/go/internal/client/plugin/build_test.go
+++ b/go/internal/client/plugin/build_test.go
@@ -1,6 +1,7 @@
package plugin
import (
+ "bd2server/internal/common/util"
"bytes"
"context"
"os"
@@ -54,7 +55,7 @@ func TestVerifiedPluginCacheSkipsSDKVersionAndCompilationStages(t *testing.T) {
}
write("plugins/LocalIdentity/bin/Release/netstandard2.1/BD2LocalIdentity.dll", "verified-output")
output := filepath.Join(root, "plugins", "LocalIdentity", "bin", "Release", "netstandard2.1", "BD2LocalIdentity.dll")
- digest, err := fileDigest(output)
+ digest, err := util.SHA256File(output)
if err != nil {
t.Fatal(err)
}
diff --git a/go/internal/client/plugin/install.go b/go/internal/client/plugin/install.go
index 95f6195..c261bec 100644
--- a/go/internal/client/plugin/install.go
+++ b/go/internal/client/plugin/install.go
@@ -1,6 +1,7 @@
package plugin
import (
+ "bd2server/internal/common/util"
"bytes"
"encoding/json"
"errors"
@@ -148,6 +149,9 @@ func InstallSet(gameDir string, sources []string) (SetResult, error) {
dropped = append(dropped, name)
}
}
+ if len(changed) == 0 && len(dropped) == 0 && slices.Equal(previous, names) {
+ return result, nil
+ }
defer func() {
for _, f := range changed {
if f.temporary != "" {
@@ -171,7 +175,7 @@ func InstallSet(gameDir string, sources []string) (SetResult, error) {
var failures []error
for _, f := range slices.Backward(replaced) {
if f.backup != "" {
- if err := commonconfig.ReplaceFile(f.backup, f.destination); err != nil {
+ if err := util.ReplaceFile(f.backup, f.destination); err != nil {
failures = append(failures, fmt.Errorf("restore %s: %w", f.name, err))
}
} else if err := os.Remove(f.destination); err != nil && !errors.Is(err, os.ErrNotExist) {
@@ -199,7 +203,7 @@ func InstallSet(gameDir string, sources []string) (SetResult, error) {
}
replaced = append(replaced, f)
if f.temporary != "" {
- if err := commonconfig.ReplaceFile(f.temporary, f.destination); err != nil {
+ if err := util.ReplaceFile(f.temporary, f.destination); err != nil {
return err
}
f.temporary = ""
diff --git a/go/internal/client/preparation/prepare.go b/go/internal/client/preparation/prepare.go
new file mode 100644
index 0000000..b619b58
--- /dev/null
+++ b/go/internal/client/preparation/prepare.go
@@ -0,0 +1,250 @@
+package preparation
+
+import (
+ "context"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "runtime"
+ "time"
+
+ clientconfig "bd2server/internal/client/config"
+ "bd2server/internal/client/download"
+ "bd2server/internal/client/layout"
+ "bd2server/internal/client/setup"
+ commonconfig "bd2server/internal/common/config"
+ "bd2server/internal/common/taskgraph"
+ "bd2server/internal/common/versionconfig"
+)
+
+type Options struct {
+ PackageDirectory, DownloadManifest, VersionConfig string
+ GameDirectory, ResourceDirectory string
+ Settings clientconfig.Settings
+ Versions versionconfig.Config
+ Workers int
+ DownloadOnly, BaseOnly, ProbeOnly, PlanOnly bool
+ DownloadIfMissing bool
+ LocalIdentityPlugin, LoginUIPlugin string
+ CashShopPlugin, FChatPlugin string
+ PrepareGame func(context.Context, string, clientconfig.Settings) (versionconfig.Config, error)
+ SavePreferences func(string) error
+}
+
+type Result struct {
+ GameDirectory, ResourceDirectory string
+ Settings clientconfig.Settings
+ Versions versionconfig.Config
+ Status setup.GameStatus
+ Plan []string
+}
+
+func Run(ctx context.Context, options Options, out io.Writer) (Result, error) {
+ var result Result
+ if options.Workers < 1 || options.Workers > 16 {
+ return result, errors.New("prepare workers must be 1-16")
+ }
+ if options.DownloadOnly && options.BaseOnly {
+ return result, errors.New("--download and --base select separate stages; omit both to run all stages")
+ }
+ if options.BaseOnly && options.ProbeOnly {
+ return result, errors.New("--probe-only cannot be used with --base")
+ }
+ if options.PackageDirectory == "" {
+ executable, err := os.Executable()
+ if err != nil {
+ return result, err
+ }
+ options.PackageDirectory = filepath.Dir(executable)
+ }
+ directory, err := filepath.Abs(options.PackageDirectory)
+ if err != nil {
+ return result, err
+ }
+ if out == nil {
+ out = io.Discard
+ }
+ result.GameDirectory, result.ResourceDirectory = options.GameDirectory, options.ResourceDirectory
+ if result.GameDirectory == "" {
+ result.GameDirectory = filepath.Join(directory, "game")
+ }
+ if result.ResourceDirectory == "" {
+ result.ResourceDirectory = options.Settings.LocalResourceDirectory
+ }
+ if result.ResourceDirectory == "" {
+ result.ResourceDirectory = filepath.Join(directory, "resources")
+ }
+ result.Settings, result.Versions = options.Settings, options.Versions
+ var downloaded versionconfig.Config
+ didDownload := false
+ graph, err := taskgraph.New(
+ taskgraph.Task{Name: "download", Run: func(ctx context.Context) error {
+ if options.DownloadIfMissing && !options.ProbeOnly {
+ if installation, err := layout.Resolve(result.GameDirectory); err == nil &&
+ (result.Settings.CDNMode != clientconfig.CDNLocal || installation.Kind == layout.MacOS) {
+ result.GameDirectory = installation.Root
+ return nil
+ }
+ if runtime.GOOS != "windows" {
+ return errors.New("automatic game installation is available only on Windows; select an installed game")
+ }
+ }
+ installed, err := download.Client(ctx, download.Options{
+ PackageDir: directory, Manifest: options.DownloadManifest,
+ GameDir: result.GameDirectory, ResourceDir: result.ResourceDirectory, ServerOrigin: result.Settings.ServerOrigin,
+ Workers: options.Workers, ProbeOnly: options.ProbeOnly,
+ }, out)
+ if err != nil {
+ return err
+ }
+ result.GameDirectory, result.ResourceDirectory = installed.GameDir, installed.ResourceDir
+ result.Settings.ServerOrigin = installed.ServerOrigin
+ downloaded, didDownload = installed.Versions, true
+ if options.DownloadOnly || options.ProbeOnly {
+ result.Versions = installed.Versions
+ }
+ return nil
+ }},
+ taskgraph.Task{Name: "base:configuration", Run: func(context.Context) error {
+ if result.Settings.ServerOrigin == "" {
+ manifest := options.DownloadManifest
+ if manifest == "" {
+ manifest = filepath.Join(directory, "client-download.json")
+ }
+ defaults, err := commonconfig.Load(manifest, struct {
+ ServerOrigin string `json:"server_origin"`
+ }{}, commonconfig.DecodeOptions{AllowBOM: true, RejectTrailing: true})
+ if err != nil {
+ return err
+ }
+ result.Settings.ServerOrigin = defaults.ServerOrigin
+ }
+ if result.Versions.GameVersion == "" {
+ path := options.VersionConfig
+ if path == "" {
+ path = filepath.Join(directory, versionconfig.FileName)
+ }
+ var err error
+ result.Versions, err = versionconfig.Load(path)
+ if err != nil {
+ return err
+ }
+ }
+ if didDownload && (result.Versions.GameVersion != downloaded.GameVersion || result.Versions.GameDataVersion != downloaded.GameDataVersion || result.Versions.BundleVersion != downloaded.BundleVersion) {
+ return errors.New("client package and download manifest versions differ")
+ }
+ return nil
+ }},
+ taskgraph.Task{Name: "base:settings", DependsOn: []string{"base:configuration"}, Run: func(context.Context) error {
+ if result.Settings.CDNMode == clientconfig.CDNLocal && result.Settings.LocalResourceDirectory == "" {
+ result.Settings.LocalResourceDirectory = result.ResourceDirectory
+ }
+ var err error
+ result.Settings, err = clientconfig.Normalize(result.Settings)
+ return err
+ }},
+ taskgraph.Task{Name: "base:update", DependsOn: []string{"base:settings"}, Run: func(ctx context.Context) error {
+ if options.PrepareGame == nil {
+ return nil
+ }
+ if saved, err := clientconfig.Load(result.GameDirectory); err == nil {
+ result.Settings.Runtime = saved.Runtime
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
+ if _, err := clientconfig.Save(result.GameDirectory, result.Settings); err != nil {
+ return err
+ }
+ versions, err := options.PrepareGame(ctx, result.GameDirectory, result.Settings)
+ if err != nil {
+ return err
+ }
+ result.Versions = versions
+ saved, err := clientconfig.Load(result.GameDirectory)
+ if err != nil {
+ return err
+ }
+ result.Settings.Runtime = saved.Runtime
+ return nil
+ }},
+ taskgraph.Task{Name: "base:resources", DependsOn: []string{"base:update"}, Run: func(ctx context.Context) error {
+ policyContext, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+ _, err := setup.FetchResourcePolicy(policyContext, nil, result.Settings, result.Versions)
+ return err
+ }},
+ taskgraph.Task{Name: "base:bepinex", DependsOn: []string{"base:resources"}, Run: func(context.Context) error {
+ installation, err := layout.Resolve(result.GameDirectory)
+ if err != nil {
+ return err
+ }
+ complete := regularFile(filepath.Join(installation.BepInEx, "core", "BepInEx.dll"))
+ if installation.Kind == layout.Windows {
+ complete = complete && regularFile(filepath.Join(installation.Root, "winhttp.dll")) && regularFile(filepath.Join(installation.Root, "doorstop_config.ini"))
+ }
+ if complete {
+ return nil
+ }
+ if installation.Kind != layout.Windows {
+ return errors.New("install BepInEx for the selected macOS game before preparing the client")
+ }
+ return download.InstallBepInEx(directory, installation.Root)
+ }},
+ taskgraph.Task{Name: "base:patch", DependsOn: []string{"base:bepinex"}, Run: func(context.Context) error {
+ if _, err := setup.SaveSettings(result.GameDirectory, result.Settings); err != nil {
+ return err
+ }
+ if result.Settings.CDNMode == clientconfig.CDNLocal {
+ if err := setup.InstallLocalCatalog(result.GameDirectory, result.Settings.LocalResourceDirectory, result.Versions.BundleVersion); err != nil {
+ return err
+ }
+ }
+ _, err := setup.Patch(result.GameDirectory)
+ return err
+ }},
+ taskgraph.Task{Name: "base:plugins", DependsOn: []string{"base:patch"}, Run: func(context.Context) error {
+ sources := []*string{&options.LocalIdentityPlugin, &options.LoginUIPlugin, &options.CashShopPlugin, &options.FChatPlugin}
+ for n, name := range []string{"BD2LocalIdentity.dll", "BD2LoginUI.dll", "BD2CashShop.dll", "BD2FChat.dll"} {
+ if *sources[n] == "" {
+ *sources[n] = filepath.Join(directory, "plugins", name)
+ }
+ }
+ _, err := setup.InstallPlugins(result.GameDirectory, options.LocalIdentityPlugin, options.LoginUIPlugin, options.CashShopPlugin, options.FChatPlugin)
+ return err
+ }},
+ taskgraph.Task{Name: "base:preferences", DependsOn: []string{"base:plugins"}, Run: func(context.Context) error {
+ save := options.SavePreferences
+ if save == nil {
+ save = clientconfig.SavePreferences
+ }
+ return save(result.GameDirectory)
+ }},
+ taskgraph.Task{Name: "base", DependsOn: []string{"base:preferences"}, Run: func(context.Context) error {
+ var err error
+ result.Status, err = setup.Inspect(result.GameDirectory, result.Versions)
+ return err
+ }},
+ taskgraph.Task{Name: "prepare", DependsOn: []string{"download", "base"}},
+ )
+ if err != nil {
+ return result, err
+ }
+ target := "prepare"
+ if options.DownloadOnly || options.ProbeOnly {
+ target = "download"
+ } else if options.BaseOnly {
+ target = "base"
+ }
+ result.Plan, err = graph.Plan(target)
+ if err != nil || options.PlanOnly {
+ return result, err
+ }
+ err = graph.Run(ctx, target)
+ return result, err
+}
+
+func regularFile(path string) bool {
+ info, err := os.Stat(path)
+ return err == nil && info.Mode().IsRegular()
+}
diff --git a/go/internal/client/setup/catalog_cache.go b/go/internal/client/setup/catalog_cache.go
new file mode 100644
index 0000000..42bd3ff
--- /dev/null
+++ b/go/internal/client/setup/catalog_cache.go
@@ -0,0 +1,107 @@
+package setup
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "strings"
+
+ commonconfig "bd2server/internal/common/config"
+ "bd2server/internal/common/resourcecatalog"
+)
+
+const localCatalogReceipt = ".bd2-local-catalog.json"
+
+type catalogFile struct {
+ Path string `json:"path"`
+ Size int64 `json:"size"`
+ Modified int64 `json:"modified"`
+}
+
+type catalogReceipt struct {
+ Schema int `json:"schema"`
+ Release string `json:"release"`
+ Cache string `json:"cache"`
+ Files []catalogFile `json:"files"`
+}
+
+func catalogStamp(path string) (catalogFile, error) {
+ info, err := os.Stat(path)
+ if err != nil {
+ return catalogFile{}, err
+ }
+ if !info.Mode().IsRegular() {
+ return catalogFile{}, fmt.Errorf("local catalog requires a regular file: %s", path)
+ }
+ return catalogFile{Path: path, Size: info.Size(), Modified: info.ModTime().UnixNano()}, nil
+}
+
+func catalogStateFiles(release, aa, cache string) []string {
+ return []string{
+ filepath.Join(release, "catalog_alpha.json"), filepath.Join(release, "catalog_alpha.hash"),
+ filepath.Join(aa, "catalog.json"), filepath.Join(aa, localBundleManifest),
+ filepath.Join(cache, "catalog_alpha.json"), filepath.Join(cache, "catalog_alpha.hash"),
+ }
+}
+
+func localCatalogCurrent(release, aa, cache string) bool {
+ receipt, err := commonconfig.Load(filepath.Join(aa, localCatalogReceipt), catalogReceipt{}, commonconfig.DecodeOptions{RejectTrailing: true})
+ paths := catalogStateFiles(release, aa, cache)
+ if err != nil || receipt.Schema != 1 || receipt.Release != release || receipt.Cache != cache || len(receipt.Files) < len(paths) {
+ return false
+ }
+ for i, file := range receipt.Files {
+ if i < len(paths) && file.Path != paths[i] {
+ return false
+ }
+ current, err := catalogStamp(file.Path)
+ if err != nil || current != file {
+ return false
+ }
+ }
+ managed, err := managedCatalogBundles(aa)
+ if err != nil || len(managed) == 0 {
+ return false
+ }
+ for relative, record := range managed {
+ for _, file := range []catalogFile{
+ {Path: filepath.Join(release, filepath.FromSlash(relative)), Size: record.SourceSize, Modified: record.SourceModified},
+ {Path: filepath.Join(aa, filepath.FromSlash(relative)), Size: record.TargetSize, Modified: record.TargetModified},
+ } {
+ current, err := catalogStamp(file.Path)
+ if err != nil || current != file {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+func recordLocalCatalog(release, aa, cache string, raw []byte) error {
+ managed, err := managedCatalogBundles(aa)
+ if err != nil {
+ return err
+ }
+ _, ids, err := resourcecatalog.Decode(raw)
+ if err != nil {
+ return err
+ }
+ paths := catalogStateFiles(release, aa, cache)
+ for _, id := range ids {
+ if relative, ok := strings.CutPrefix(id, localCatalogPrefix); ok {
+ relative = strings.ReplaceAll(relative, "\\", "/")
+ if _, exists := managed[relative]; !exists {
+ paths = append(paths, filepath.Join(aa, filepath.FromSlash(relative)))
+ }
+ }
+ }
+ receipt := catalogReceipt{Schema: 1, Release: release, Cache: cache}
+ for _, path := range paths {
+ file, err := catalogStamp(path)
+ if err != nil {
+ return err
+ }
+ receipt.Files = append(receipt.Files, file)
+ }
+ return commonconfig.Save(filepath.Join(aa, localCatalogReceipt), receipt, commonconfig.WriteOptions{})
+}
diff --git a/go/internal/client/setup/local_catalog.go b/go/internal/client/setup/local_catalog.go
index 98a1a31..e4b82bc 100644
--- a/go/internal/client/setup/local_catalog.go
+++ b/go/internal/client/setup/local_catalog.go
@@ -9,10 +9,13 @@ import (
"os"
"path/filepath"
"runtime"
+ "slices"
"strings"
+ "bd2server/internal/client/download"
clientlayout "bd2server/internal/client/layout"
"bd2server/internal/common/resourcecatalog"
+ "bd2server/internal/common/util"
)
const (
@@ -28,30 +31,63 @@ func InstallLocalCatalog(gameDir, localRoot, bundleVersion string) error {
return err
}
release := filepath.Join(filepath.Clean(localRoot), "ServerData", "StandaloneWindows64", "HD", bundleVersion)
- source := filepath.Join(release, "catalog_alpha.json")
- sourceHash := filepath.Join(release, "catalog_alpha.hash")
- raw, err := readCatalog(source)
+ aa := filepath.Join(installation.Data, "StreamingAssets", "aa")
+ cache, err := addressablesCacheDirectory(installation)
if err != nil {
return err
}
- aa := filepath.Join(installation.Data, "StreamingAssets", "aa")
+ if err := separateCatalogDirectories(release, aa, cache); err != nil {
+ return err
+ }
+ for _, entry := range []struct{ root, relative string }{
+ {release, "catalog_alpha.json"}, {release, "catalog_alpha.hash"},
+ {aa, "catalog.json"}, {aa, localCatalogBackup}, {aa, localBundleManifest}, {aa, localCatalogReceipt},
+ {cache, "catalog_alpha.json"}, {cache, "catalog_alpha.hash"},
+ } {
+ if _, err := catalogFilePath(entry.root, entry.relative); err != nil {
+ return err
+ }
+ }
managed, err := managedCatalogBundles(aa)
if err != nil {
return err
}
+ for relative := range managed {
+ for _, root := range []string{release, aa} {
+ if _, err := catalogFilePath(root, relative); err != nil {
+ return err
+ }
+ }
+ }
+ if localCatalogCurrent(release, aa, cache) {
+ return nil
+ }
+ source := filepath.Join(release, "catalog_alpha.json")
+ sourceHash := filepath.Join(release, "catalog_alpha.hash")
+ raw, err := readCatalog(source)
+ if err != nil {
+ return err
+ }
paths, err := resourcecatalog.BundlePaths(raw)
if err != nil {
return err
}
- raw, err = localizeCatalog(raw, release, aa, managed)
- if err != nil {
- return err
- }
target := filepath.Join(aa, "catalog.json")
current, err := os.ReadFile(target)
if err != nil {
return fmt.Errorf("read built-in Addressables catalog: %w", err)
}
+ hash, err := os.ReadFile(sourceHash)
+ if err != nil {
+ return fmt.Errorf("read local ServerData catalog hash: %w", err)
+ }
+ if len(hash) == 0 || len(hash) > 1024 {
+ return errors.New("local ServerData catalog hash has an invalid size")
+ }
+ raw, err = localizeCatalog(raw, release, aa, managed)
+ if err != nil {
+ return err
+ }
if !bytes.Equal(current, raw) {
backup := filepath.Join(aa, localCatalogBackup)
if _, err := os.Stat(backup); errors.Is(err, os.ErrNotExist) {
@@ -81,21 +117,18 @@ func InstallLocalCatalog(gameDir, localRoot, bundleVersion string) error {
if err != nil {
return err
}
+ if err := synchronizePersistentCatalog(cache, raw, hash); err != nil {
+ return err
+ }
+ if installation.Kind == clientlayout.Windows {
+ if err := download.RecordPreparedGame(gameDir, "BrownDust II_Data/StreamingAssets/aa/catalog.json"); err != nil {
+ return err
+ }
+ }
if err := replaceCatalog(filepath.Join(aa, localBundleManifest), managedRaw); err != nil {
return fmt.Errorf("record managed Addressables bundles: %w", err)
}
- hash, err := os.ReadFile(sourceHash)
- if err != nil {
- return fmt.Errorf("read local ServerData catalog hash: %w", err)
- }
- if len(hash) == 0 || len(hash) > 1024 {
- return errors.New("local ServerData catalog hash has an invalid size")
- }
- cache, err := addressablesCacheDirectory(installation)
- if err != nil {
- return err
- }
- return synchronizePersistentCatalog(cache, raw, hash)
+ return recordLocalCatalog(release, aa, cache, raw)
}
func addressablesCacheDirectory(installation clientlayout.Installation) (string, error) {
@@ -222,24 +255,38 @@ func localizeCatalog(raw []byte, release, aa string, managed map[string]managedB
return nil, err
}
remoteCount := 0
+ type bundleLink struct{ source, destination, relative string }
+ var links []bundleLink
for index, internalID := range ids {
if strings.HasPrefix(internalID, resourcecatalog.RemotePrefix) {
relative, err := resourcecatalog.BundlePath(internalID)
if err != nil {
return nil, err
}
- source := filepath.Join(release, filepath.FromSlash(relative))
- destination := filepath.Join(aa, filepath.FromSlash(relative))
- if err := ensureCatalogBundleLink(source, destination, managed[relative]); err != nil {
+ source, err := catalogFilePath(release, relative)
+ if err != nil {
return nil, err
}
+ info, err := os.Stat(source)
+ if err != nil || !info.Mode().IsRegular() {
+ return nil, fmt.Errorf("local ServerData catalog references a missing bundle: %s", source)
+ }
+ destination, err := catalogFilePath(aa, relative)
+ if err != nil {
+ return nil, err
+ }
+ links = append(links, bundleLink{source, destination, relative})
ids[index] = localCatalogPrefix + strings.ReplaceAll(filepath.ToSlash(relative), "/", "\\")
remoteCount++
continue
}
if relative, ok := strings.CutPrefix(internalID, localCatalogPrefix); ok {
- relative = filepath.FromSlash(strings.ReplaceAll(relative, "\\", "/"))
- if info, err := os.Stat(filepath.Join(aa, relative)); err != nil || !info.Mode().IsRegular() {
+ relative = strings.ReplaceAll(relative, "\\", "/")
+ path, err := catalogFilePath(aa, relative)
+ if err != nil {
+ return nil, err
+ }
+ if info, err := os.Stat(path); err != nil || !info.Mode().IsRegular() {
return nil, fmt.Errorf("built-in Addressables catalog references a missing local bundle: %s", relative)
}
}
@@ -256,6 +303,11 @@ func localizeCatalog(raw []byte, release, aa string, managed map[string]managedB
if err != nil {
return nil, fmt.Errorf("encode localized ServerData catalog: %w", err)
}
+ for _, link := range links {
+ if err := ensureCatalogBundleLink(link.source, link.destination, managed[link.relative]); err != nil {
+ return nil, err
+ }
+ }
return localized, nil
}
@@ -264,19 +316,29 @@ func ensureCatalogBundleLink(source, destination string, managed managedBundle)
if err != nil || !sourceInfo.Mode().IsRegular() {
return fmt.Errorf("local ServerData catalog references a missing bundle: %s", source)
}
- if destinationInfo, err := os.Stat(destination); err == nil {
+ if destinationInfo, err := os.Lstat(destination); err == nil {
if !destinationInfo.Mode().IsRegular() {
return fmt.Errorf("game Addressables bundle conflicts with the selected local release: %s", destination)
}
if os.SameFile(sourceInfo, destinationInfo) {
return nil
}
- if managed.Path == "" {
- return fmt.Errorf("game Addressables bundle conflicts with the selected local release: %s", destination)
- }
- if sourceInfo.Size() == managed.SourceSize && sourceInfo.ModTime().UnixNano() == managed.SourceModified && destinationInfo.Size() == managed.TargetSize && destinationInfo.ModTime().UnixNano() == managed.TargetModified {
+ if managed.Path != "" && sourceInfo.Size() == managed.SourceSize && sourceInfo.ModTime().UnixNano() == managed.SourceModified && destinationInfo.Size() == managed.TargetSize && destinationInfo.ModTime().UnixNano() == managed.TargetModified {
return nil
}
+ if sourceInfo.Size() == destinationInfo.Size() {
+ sourceHash, err := util.SHA256File(source)
+ if err != nil {
+ return err
+ }
+ targetHash, err := util.SHA256File(destination)
+ if err != nil {
+ return err
+ }
+ if sourceHash == targetHash {
+ return nil
+ }
+ }
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("inspect game Addressables bundle: %w", err)
}
@@ -314,7 +376,85 @@ func ensureCatalogBundleLink(source, destination string, managed managedBundle)
return errors.New("incomplete local Addressables bundle copy")
}
}
- return os.Rename(path, destination)
+ return util.ReplaceFile(path, destination)
+}
+
+func catalogFilePath(root, relative string) (string, error) {
+ root, err := filepath.Abs(root)
+ if err != nil {
+ return "", err
+ }
+ if !filepath.IsLocal(filepath.FromSlash(relative)) {
+ return "", errors.New("catalog file path must be relative to its directory")
+ }
+ target := filepath.Join(root, filepath.FromSlash(relative))
+ rel, err := filepath.Rel(root, target)
+ if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+ return "", errors.New("catalog file escapes its directory")
+ }
+ for path := target; ; path = filepath.Dir(path) {
+ info, err := os.Lstat(path)
+ if err == nil {
+ if info.Mode()&os.ModeSymlink != 0 {
+ return "", fmt.Errorf("catalog path contains a symbolic link: %s", path)
+ }
+ if path == target && !info.Mode().IsRegular() || path != target && !info.IsDir() {
+ return "", fmt.Errorf("catalog path conflicts with a non-regular file or directory: %s", path)
+ }
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return "", err
+ }
+ if path == root {
+ break
+ }
+ }
+ return target, nil
+}
+
+func resolvedCatalogPath(path string) (string, error) {
+ path, err := filepath.Abs(path)
+ if err != nil {
+ return "", err
+ }
+ var suffix []string
+ for {
+ resolved, err := filepath.EvalSymlinks(path)
+ if err == nil {
+ for _, part := range slices.Backward(suffix) {
+ resolved = filepath.Join(resolved, part)
+ }
+ return resolved, nil
+ }
+ if !errors.Is(err, os.ErrNotExist) {
+ return "", err
+ }
+ parent := filepath.Dir(path)
+ if parent == path {
+ return "", err
+ }
+ suffix = append(suffix, filepath.Base(path))
+ path = parent
+ }
+}
+
+func separateCatalogDirectories(release string, outputs ...string) error {
+ source, err := resolvedCatalogPath(release)
+ if err != nil {
+ return err
+ }
+ for _, output := range outputs {
+ target, err := resolvedCatalogPath(output)
+ if err != nil {
+ return err
+ }
+ for _, pair := range [][2]string{{source, target}, {target, source}} {
+ rel, err := filepath.Rel(pair[0], pair[1])
+ if err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+ return errors.New("local resource source and game output directories must not overlap")
+ }
+ }
+ }
+ return nil
}
func writeExclusiveFile(path string, data []byte, mode os.FileMode) error {
@@ -332,6 +472,11 @@ func writeExclusiveFile(path string, data []byte, mode os.FileMode) error {
}
func replaceCatalog(path string, data []byte) error {
+ if current, err := os.ReadFile(path); err == nil && bytes.Equal(current, data) {
+ return nil
+ } else if err != nil && !errors.Is(err, os.ErrNotExist) {
+ return err
+ }
temporary, err := os.CreateTemp(filepath.Dir(path), ".catalog-local-*.json")
if err != nil {
return err
diff --git a/go/internal/client/setup/local_catalog_test.go b/go/internal/client/setup/local_catalog_test.go
index b2a1d31..9258823 100644
--- a/go/internal/client/setup/local_catalog_test.go
+++ b/go/internal/client/setup/local_catalog_test.go
@@ -1,6 +1,8 @@
package setup
import (
+ "bytes"
+ "encoding/json"
"os"
"path/filepath"
"runtime"
@@ -9,6 +11,211 @@ import (
"time"
)
+type catalogScenario struct{ game, resources, aa, release string }
+
+func newCatalogScenario(t *testing.T, remote ...string) catalogScenario {
+ t.Helper()
+ root := t.TempDir()
+ s := catalogScenario{game: filepath.Join(root, "instance", "game"), resources: filepath.Join(root, "resources")}
+ s.aa = filepath.Join(s.game, "BrownDust II_Data", "StreamingAssets", "aa")
+ s.release = filepath.Join(s.resources, "ServerData", "StandaloneWindows64", "HD", "20261007175947")
+ s.write(t, filepath.Join(s.game, "BrownDust II.exe"), "game")
+ s.write(t, filepath.Join(s.game, "BrownDust II_Data", "resources.assets"), "assets")
+ s.write(t, filepath.Join(root, "instance", "instance.json"), `{"schema_version":1,"id":"instance"}`)
+ s.write(t, filepath.Join(s.aa, "catalog.json"), `{"m_InternalIds":["{UnityEngine.AddressableAssets.Addressables.RuntimePath}\\builtin.bundle"]}`)
+ s.write(t, filepath.Join(s.aa, "builtin.bundle"), "builtin bytes")
+ ids := []string{localCatalogPrefix + "builtin.bundle"}
+ for _, relative := range remote {
+ ids = append(ids, "{BDNetwork.CdnInfo.Info}/StandaloneWindows64/HD/20261007175947/"+relative)
+ }
+ raw, err := json.Marshal(map[string]any{"m_InternalIds": ids})
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.write(t, filepath.Join(s.release, "catalog_alpha.json"), string(raw))
+ s.write(t, filepath.Join(s.release, "catalog_alpha.hash"), "0f90a94601be05737f86a4ec7a1c889f")
+ return s
+}
+func (s catalogScenario) write(t *testing.T, path, value string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(value), 0600); err != nil {
+ t.Fatal(err)
+ }
+}
+func (s catalogScenario) install() error {
+ return InstallLocalCatalog(s.game, s.resources, "20261007175947")
+}
+func catalogTree(t *testing.T, root string) map[string][]byte {
+ t.Helper()
+ files := map[string][]byte{}
+ if err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if entry.IsDir() {
+ return nil
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ relative, err := filepath.Rel(root, path)
+ if err != nil {
+ return err
+ }
+ files[relative] = data
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ return files
+}
+func assertCatalogTree(t *testing.T, root string, before map[string][]byte) {
+ t.Helper()
+ after := catalogTree(t, root)
+ if len(after) != len(before) {
+ t.Fatalf("rejected synchronization changed file count: %d -> %d", len(before), len(after))
+ }
+ for path, data := range before {
+ if !bytes.Equal(data, after[path]) {
+ t.Fatalf("rejected synchronization changed %s", path)
+ }
+ }
+}
+
+func TestIncompleteCatalogDoesNotPartiallyInstallAndRetryAdoptsCopiedBundle(t *testing.T) {
+ s := newCatalogScenario(t, "a-first.bundle", "z-missing.bundle")
+ s.write(t, filepath.Join(s.release, "a-first.bundle"), "current first")
+ s.write(t, filepath.Join(s.aa, "a-first.bundle"), "existing first")
+ before := catalogTree(t, s.game)
+ if err := s.install(); err == nil {
+ t.Fatal("incomplete source catalog was installed")
+ }
+ assertCatalogTree(t, s.game, before)
+ s.write(t, filepath.Join(s.release, "z-missing.bundle"), "last bundle")
+ s.write(t, filepath.Join(s.aa, "a-first.bundle"), "current first")
+ partial, err := os.Stat(filepath.Join(s.aa, "a-first.bundle"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ source, err := os.Stat(filepath.Join(s.release, "a-first.bundle"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if os.SameFile(partial, source) {
+ t.Fatal("partial-install scenario must exercise an independent copy")
+ }
+ if err := s.install(); err != nil {
+ t.Fatalf("retry rejected an unrecorded completed copy: %v", err)
+ }
+ after, err := os.Stat(filepath.Join(s.aa, "a-first.bundle"))
+ if err != nil || !os.SameFile(partial, after) || !partial.ModTime().Equal(after.ModTime()) {
+ t.Fatal("retry unnecessarily replaced the matching partial copy")
+ }
+ if actual, err := os.ReadFile(filepath.Join(s.aa, "z-missing.bundle")); err != nil || string(actual) != "last bundle" {
+ t.Fatal("retry did not finish the remaining bundle")
+ }
+ if actual, err := os.ReadFile(filepath.Join(s.aa, "builtin.bundle")); err != nil || string(actual) != "builtin bytes" {
+ t.Fatal("retry changed an unrelated built-in bundle")
+ }
+ if _, err := os.Stat(filepath.Join(s.aa, localBundleManifest)); err != nil {
+ t.Fatal("completed retry did not publish its managed bundle record")
+ }
+}
+
+func TestAuthoritativeRemoteBundleReplacesUnrecordedOldContent(t *testing.T) {
+ s := newCatalogScenario(t, "scene.bundle")
+ s.write(t, filepath.Join(s.release, "scene.bundle"), "current release")
+ s.write(t, filepath.Join(s.aa, "scene.bundle"), "previous release")
+ if err := s.install(); err != nil {
+ t.Fatal(err)
+ }
+ if actual, err := os.ReadFile(filepath.Join(s.aa, "scene.bundle")); err != nil || string(actual) != "current release" {
+ t.Fatal("remote catalog entry kept unrecorded outdated content")
+ }
+ if actual, err := os.ReadFile(filepath.Join(s.aa, "builtin.bundle")); err != nil || string(actual) != "builtin bytes" {
+ t.Fatal("remote synchronization modified unrelated builtin content")
+ }
+ if actual, err := os.ReadFile(filepath.Join(s.release, "scene.bundle")); err != nil || string(actual) != "current release" {
+ t.Fatal("synchronization modified the source resource")
+ }
+}
+
+func TestCatalogRejectsSourceOutputAliasAndDirectoryConflictsBeforeCopy(t *testing.T) {
+ t.Run("game output nested inside source", func(t *testing.T) {
+ s := newCatalogScenario(t, "scene.bundle")
+ oldGame := s.game
+ s.game = filepath.Join(s.release, "instance", "game")
+ s.aa = filepath.Join(s.game, "BrownDust II_Data", "StreamingAssets", "aa")
+ for relative, data := range catalogTree(t, oldGame) {
+ s.write(t, filepath.Join(s.game, relative), string(data))
+ }
+ s.write(t, filepath.Join(s.release, "instance", "instance.json"), `{"schema_version":1,"id":"instance"}`)
+ s.write(t, filepath.Join(s.release, "scene.bundle"), "source must survive")
+ before := catalogTree(t, s.release)
+ if err := s.install(); err == nil {
+ t.Fatal("game output nested inside resource input was accepted")
+ }
+ assertCatalogTree(t, s.release, before)
+ })
+ t.Run("source aliases game output", func(t *testing.T) {
+ s := newCatalogScenario(t, "scene.bundle")
+ for _, name := range []string{"catalog_alpha.json", "catalog_alpha.hash"} {
+ data, err := os.ReadFile(filepath.Join(s.release, name))
+ if err != nil {
+ t.Fatal(err)
+ }
+ s.write(t, filepath.Join(s.aa, name), string(data))
+ }
+ s.write(t, filepath.Join(s.aa, "scene.bundle"), "aliased source")
+ if err := os.RemoveAll(s.release); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(s.aa, s.release); err != nil {
+ t.Skipf("symbolic links unavailable: %v", err)
+ }
+ before := catalogTree(t, s.aa)
+ if err := s.install(); err == nil {
+ t.Fatal("source/output directory alias was accepted")
+ }
+ assertCatalogTree(t, s.aa, before)
+ })
+ t.Run("target directory", func(t *testing.T) {
+ s := newCatalogScenario(t, "a-first.bundle", "z-conflict.bundle")
+ s.write(t, filepath.Join(s.release, "a-first.bundle"), "first")
+ s.write(t, filepath.Join(s.release, "z-conflict.bundle"), "last")
+ if err := os.Mkdir(filepath.Join(s.aa, "z-conflict.bundle"), 0700); err != nil {
+ t.Fatal(err)
+ }
+ before := catalogTree(t, s.game)
+ if err := s.install(); err == nil {
+ t.Fatal("bundle target directory was overwritten")
+ }
+ assertCatalogTree(t, s.game, before)
+ })
+ t.Run("target symbolic link", func(t *testing.T) {
+ s := newCatalogScenario(t, "scene.bundle")
+ s.write(t, filepath.Join(s.release, "scene.bundle"), "release bytes")
+ other := filepath.Join(t.TempDir(), "outside.bundle")
+ s.write(t, other, "keep outside")
+ if err := os.Symlink(other, filepath.Join(s.aa, "scene.bundle")); err != nil {
+ t.Skipf("symbolic links unavailable: %v", err)
+ }
+ if err := s.install(); err == nil {
+ t.Fatal("bundle target symbolic link was accepted")
+ }
+ if actual, err := os.ReadFile(other); err != nil || string(actual) != "keep outside" {
+ t.Fatal("target alias modified an unrelated file")
+ }
+ if _, err := os.Stat(filepath.Join(s.aa, localBundleManifest)); !os.IsNotExist(err) {
+ t.Fatal("rejected alias published a managed manifest")
+ }
+ })
+}
+
func TestLocalCatalogRefreshReplacesManagedBundlesAndPreservesBuiltins(t *testing.T) {
root := t.TempDir()
resources := t.TempDir()
@@ -91,4 +298,48 @@ func TestLocalCatalogRefreshReplacesManagedBundlesAndPreservesBuiltins(t *testin
if !os.SameFile(installed, unchanged) {
t.Fatal("unchanged cached resource was unnecessarily replaced")
}
+ cache := filepath.Join(root, "instance", "unity", "persistent", "com.unity.addressables")
+ stable := map[string]os.FileInfo{}
+ for _, path := range []string{filepath.Join(aa, "catalog.json"), filepath.Join(aa, localBundleManifest), filepath.Join(cache, "catalog_alpha.json"), filepath.Join(cache, "catalog_alpha.hash")} {
+ info, err := os.Stat(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ stable[path] = info
+ }
+ if err := InstallLocalCatalog(game, resources, version); err != nil {
+ t.Fatal(err)
+ }
+ for path, previous := range stable {
+ current, err := os.Stat(path)
+ if err != nil || !os.SameFile(previous, current) || !previous.ModTime().Equal(current.ModTime()) {
+ t.Fatalf("unchanged preparation rewrote %s: %v", path, err)
+ }
+ }
+ if err := os.Remove(streamed); err != nil {
+ t.Fatal(err)
+ }
+ if err := InstallLocalCatalog(game, resources, version); err != nil {
+ t.Fatal(err)
+ }
+ if actual, err := os.ReadFile(streamed); err != nil || string(actual) != "new bytes" {
+ t.Fatalf("cached preparation did not restore the missing current bundle: %q, %v", actual, err)
+ }
+ persistentCatalog := filepath.Join(cache, "catalog_alpha.json")
+ if err := os.Remove(persistentCatalog); err != nil {
+ t.Fatal(err)
+ }
+ if err := InstallLocalCatalog(game, resources, version); err != nil {
+ t.Fatal(err)
+ }
+ gameCatalog, err := os.ReadFile(filepath.Join(aa, "catalog.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if actual, err := os.ReadFile(persistentCatalog); err != nil || string(actual) != string(gameCatalog) {
+ t.Fatalf("cached preparation did not restore the persistent catalog: %v", err)
+ }
+ if actual, err := os.ReadFile(filepath.Join(aa, "builtin.bundle")); err != nil || string(actual) != "keep builtin" {
+ t.Fatalf("repair modified the unrelated built-in bundle: %q, %v", actual, err)
+ }
}
diff --git a/go/internal/client/setup/settings_test.go b/go/internal/client/setup/settings_test.go
new file mode 100644
index 0000000..9dfae95
--- /dev/null
+++ b/go/internal/client/setup/settings_test.go
@@ -0,0 +1,40 @@
+package setup
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ clientconfig "bd2server/internal/client/config"
+)
+
+func TestSaveLocalSettingsBeforeGameAndResourcesAreInstalled(t *testing.T) {
+ root := t.TempDir()
+ game, resources := filepath.Join(root, "game"), filepath.Join(root, "resources")
+ input := clientconfig.Settings{ServerOrigin: "https://play.example.com", CDNMode: clientconfig.CDNLocal, LocalResourceDirectory: resources}
+ if _, err := SaveSettings(game, input); err != nil {
+ t.Fatal("saving an installation location depended on game or resource preparation", err)
+ }
+ saved, err := clientconfig.Load(game)
+ if err != nil || saved.ServerOrigin != input.ServerOrigin || saved.CDNMode != input.CDNMode || saved.LocalResourceDirectory != resources {
+ t.Fatalf("saved settings could not be restored for preparation: %+v, %v", saved, err)
+ }
+ if _, err := os.Stat(resources); !os.IsNotExist(err) {
+ t.Fatal("saving settings tried to create the resource installation", err)
+ }
+ if _, err := os.Stat(filepath.Join(game, "BrownDust II_Data")); !os.IsNotExist(err) {
+ t.Fatal("saving settings tried to prepare the game", err)
+ }
+ configPath := clientconfig.Path(game)
+ before, err := os.Stat(configPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := SaveSettings(game, input); err != nil {
+ t.Fatal(err)
+ }
+ after, err := os.Stat(configPath)
+ if err != nil || !os.SameFile(before, after) || !before.ModTime().Equal(after.ModTime()) {
+ t.Fatal("saving unchanged settings rewrote the configuration", err)
+ }
+}
diff --git a/go/internal/client/setup/setup.go b/go/internal/client/setup/setup.go
index e892f9a..6010c99 100644
--- a/go/internal/client/setup/setup.go
+++ b/go/internal/client/setup/setup.go
@@ -20,6 +20,7 @@ import (
"time"
clientconfig "bd2server/internal/client/config"
+ "bd2server/internal/client/download"
"bd2server/internal/client/introdb"
clientlayout "bd2server/internal/client/layout"
"bd2server/internal/client/plugin"
@@ -52,6 +53,10 @@ type ResourcePolicy struct {
type InstallResult = plugin.SetResult
func Inspect(gameDir string, versions versionconfig.Config) (GameStatus, error) {
+ return inspect(gameDir, versions, true)
+}
+
+func inspect(gameDir string, versions versionconfig.Config, verifyPatch bool) (GameStatus, error) {
if strings.TrimSpace(gameDir) == "" {
return GameStatus{}, errors.New("select the Brown Dust II installation directory")
}
@@ -71,15 +76,17 @@ func Inspect(gameDir string, versions versionconfig.Config) (GameStatus, error)
if status.ClientVersion != versions.GameVersion {
return status, fmt.Errorf("unsupported Brown Dust II client version %s; this bd2client release requires %s", status.ClientVersion, versions.GameVersion)
}
- if verified, verifyErr := introdb.VerifyClient(installation.Root); verifyErr == nil {
- status.PatchedURL = verified.URL
+ if verifyPatch {
+ if verified, verifyErr := introdb.VerifyClient(installation.Root); verifyErr == nil {
+ status.PatchedURL = verified.URL
+ }
}
return status, nil
}
-func SaveSettings(gameDir string, settings clientconfig.Settings, versions versionconfig.Config) (clientconfig.Settings, error) {
- if _, err := Inspect(gameDir, versions); err != nil {
- return clientconfig.Settings{}, err
+func SaveSettings(gameDir string, settings clientconfig.Settings) (clientconfig.Settings, error) {
+ if strings.TrimSpace(gameDir) == "" {
+ return clientconfig.Settings{}, errors.New("select the Brown Dust II installation directory")
}
normalized, err := clientconfig.Normalize(settings)
if err != nil {
@@ -92,50 +99,37 @@ func SaveSettings(gameDir string, settings clientconfig.Settings, versions versi
return clientconfig.Settings{}, err
}
}
- if normalized.CDNMode == clientconfig.CDNLocal {
- if err := InstallLocalCatalog(gameDir, normalized.LocalResourceDirectory, versions.BundleVersion); err != nil {
- return clientconfig.Settings{}, err
- }
- }
return clientconfig.Save(gameDir, normalized)
}
-func Patch(gameDir string, settings clientconfig.Settings, versions versionconfig.Config) (introdb.Result, error) {
- if _, err := SaveSettings(gameDir, settings, versions); err != nil {
- return introdb.Result{}, err
- }
+func Patch(gameDir string) (introdb.Result, error) {
result, err := introdb.PatchClient(gameDir, PatchPlaceholder)
if err != nil {
return introdb.Result{}, err
}
- if _, err := introdb.VerifyClient(gameDir); err != nil {
- return introdb.Result{}, fmt.Errorf("verify patched client resources: %w", err)
- }
if _, err := disableLegacyPlugin(gameDir); err != nil {
return introdb.Result{}, err
}
+ if err := download.RecordPreparedGame(gameDir, "BrownDust II_Data/resources.assets"); err != nil {
+ return introdb.Result{}, err
+ }
return result, nil
}
func InstallPlugins(
gameDir string,
- settings clientconfig.Settings,
- versions versionconfig.Config,
localIdentitySource string,
loginUISource string,
cashShopSource string,
fChatSource string,
) (InstallResult, error) {
- status, err := Inspect(gameDir, versions)
+ installation, err := clientlayout.Resolve(gameDir)
if err != nil {
return InstallResult{}, err
}
- if !status.BepInEx {
+ if !regularFile(filepath.Join(installation.BepInEx, "core", "BepInEx.dll")) {
return InstallResult{}, fmt.Errorf("BepInEx is not installed; install it from %s before installing the plugins", plugin.BepInExReleasesURL)
}
- if _, err := SaveSettings(gameDir, settings, versions); err != nil {
- return InstallResult{}, err
- }
var sources []string
for spec, explicit := range map[plugin.Spec]string{plugin.LocalIdentity: localIdentitySource, plugin.LoginUI: loginUISource, plugin.CashShop: cashShopSource, plugin.FChat: fChatSource} {
source, err := plugin.ResolvePackaged(spec, explicit)
diff --git a/go/internal/client/update/game.go b/go/internal/client/update/game.go
index 39cf19a..acfd853 100644
--- a/go/internal/client/update/game.go
+++ b/go/internal/client/update/game.go
@@ -1,6 +1,7 @@
package update
import (
+ "bd2server/internal/common/util"
"context"
"errors"
"fmt"
@@ -116,6 +117,7 @@ func (m *Manager) ensureGame(ctx context.Context, game string) error {
if fp.RequireClientUpdate && clientUpdateRequired(m.options.Versions.ClientVersion, fp.ClientVersion) {
return fmt.Errorf("update the launcher to %s before updating the game", fp.ClientVersion)
}
+ m.options.Logger.Info("game installation does not match the server requirement", "game", game, "requirement", fp.ID, "game_version", gameVersion(fp))
reuseResources := previousErr == nil && previous.ResourceFingerprint == fp.GameFingerprint && fp.GameFingerprint != "" && len(previous.Files) > 0 && gameReceiptMatches(game, previous.Fingerprint)
installGame := fp.RequireGameUpdate && !reuseResources
if installGame {
@@ -155,13 +157,17 @@ func (m *Manager) ensureGame(ctx context.Context, game string) error {
if resources == "" {
resources = filepath.Join(m.options.Directory, "resources")
}
+ m.options.Logger.Info("downloading required game and resources", "game", game, "resources", resources, "game_version", fp.Game.GameVersion, "bundle_version", fp.Game.BundleVersion, "game_data_version", fp.Game.GameDataVersion)
installed, err := download.Client(ctx, download.Options{PackageDir: m.options.Directory, GameDir: game, ResourceDir: resources, Workers: 8, Pinned: fp.Game}, io.Discard)
if err != nil {
return err
}
v.GameVersion, v.BundleVersion, v.GameDataVersion = installed.Versions.GameVersion, installed.Versions.BundleVersion, installed.Versions.GameDataVersion
resources = installed.ResourceDir
- if _, err := setup.Patch(game, settings, v); err != nil {
+ if _, err := setup.SaveSettings(game, settings); err != nil {
+ return fmt.Errorf("restore game connection settings: %w", err)
+ }
+ if _, err := setup.Patch(game); err != nil {
return fmt.Errorf("restore game connection patch: %w", err)
}
if err := setup.InstallLocalCatalog(game, resources, v.BundleVersion); err != nil {
@@ -197,7 +203,7 @@ func (m *Manager) ensureGame(ctx context.Context, game string) error {
if err != nil {
return err
}
- digest, err := release.HashFile(path)
+ digest, err := util.SHA256File(path)
if err != nil {
return err
}
@@ -209,6 +215,7 @@ func (m *Manager) ensureGame(ctx context.Context, game string) error {
if err := commonconfig.Save(filepath.Join(game, gameReceiptFile), receipt, commonconfig.WriteOptions{FileMode: 0644}); err != nil {
return err
}
+ m.options.Logger.Info("game installation recorded for the server requirement", "game", game, "requirement", fp.ID, "downloaded", installGame, "reused_resources", reuseResources, "verified_files", len(receipt.Files))
m.mu.Lock()
delete(m.gamePending, game)
if len(m.gamePending) == 0 {
@@ -268,8 +275,8 @@ func (m *Manager) installGameUpdates(ctx context.Context) {
// PrepareGame resolves the server's signed requirement before inspecting a
// possibly obsolete game installation with the new release's versions.
func (m *Manager) PrepareGame(ctx context.Context, game, origin string) error {
- if !m.begin("preparing") {
- return operationBusy()
+ if err := m.acquire(ctx, "preparing"); err != nil {
+ return err
}
defer m.end()
if err := m.CheckServer(ctx, m.options.Client, origin); err != nil {
@@ -339,3 +346,10 @@ func (m *Manager) clearServerRequirement() {
m.fingerprint = nil
m.mu.Unlock()
}
+
+func gameVersion(fp *release.Fingerprint) string {
+ if fp.Game == nil {
+ return ""
+ }
+ return fp.Game.GameVersion
+}
diff --git a/go/internal/client/update/manager.go b/go/internal/client/update/manager.go
index f16c33b..2fbc015 100644
--- a/go/internal/client/update/manager.go
+++ b/go/internal/client/update/manager.go
@@ -6,6 +6,7 @@
package update
import (
+ "bd2server/internal/common/util"
"context"
"encoding/json"
"errors"
@@ -93,7 +94,7 @@ type Manager struct {
manifestURL string
keys []release.TrustedKey
- operation sync.Mutex
+ operation chan struct{}
envelope []byte
mu sync.Mutex
status Status
@@ -109,7 +110,7 @@ func New(options Options) *Manager {
options.Logger = slog.Default()
}
address := release.BuiltinChannel().ManifestURL
- m := &Manager{options: options, manifestURL: address, keys: release.BuiltinChannel().TrustedKeys, pending: map[string]bool{}, gamePending: map[string]bool{}}
+ m := &Manager{options: options, manifestURL: address, keys: release.BuiltinChannel().TrustedKeys, pending: map[string]bool{}, gamePending: map[string]bool{}, operation: make(chan struct{}, 1)}
m.status.Enabled = address != "" && !options.Development
m.loadPackagedFingerprint()
if result := TakeResult(options.Directory); result != nil {
@@ -176,14 +177,39 @@ func operationBusy() error {
}
func (m *Manager) begin(busy string) bool {
- if !m.operation.TryLock() {
+ select {
+ case m.operation <- struct{}{}:
+ m.setBusy(busy)
+ return true
+ default:
return false
}
- m.setBusy(busy)
- return true
}
-func (m *Manager) end() { m.setBusy(""); m.operation.Unlock() }
+// acquire waits for a running background operation, so an action the player
+// asked for runs after it instead of failing.
+func (m *Manager) acquire(ctx context.Context, busy string) error {
+ select {
+ case m.operation <- struct{}{}:
+ m.setBusy(busy)
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+func (m *Manager) end() { m.setBusy(""); <-m.operation }
+
+// WaitIdle waits until no update operation is running.
+func (m *Manager) WaitIdle(ctx context.Context) error {
+ select {
+ case m.operation <- struct{}{}:
+ <-m.operation
+ return nil
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
// Run checks shortly after start and then every six hours, downloads what
// is newer, installs a downloaded plugin set wherever no game runs, and
@@ -211,20 +237,25 @@ func (m *Manager) Run(ctx context.Context) {
}
func (m *Manager) refresh(ctx context.Context) {
+ warn := func(message string, err error) {
+ if ctx.Err() == nil {
+ m.options.Logger.Warn(message, "error", err)
+ }
+ }
if err := m.Check(ctx); err != nil {
- m.options.Logger.Warn("update check failed", "error", err)
+ warn("update check failed", err)
return
}
if err := m.Download(ctx); err != nil {
- m.options.Logger.Warn("update download failed", "error", err)
+ warn("update download failed", err)
return
}
if err := m.CommitPlugins(); err != nil {
- m.options.Logger.Warn("plugin update not installed", "error", err)
+ warn("plugin update not installed", err)
return
}
if err := m.CommitGame(ctx); err != nil {
- m.options.Logger.Warn("game resources not installed", "error", err)
+ warn("game resources not installed", err)
}
}
@@ -270,9 +301,39 @@ func (m *Manager) Check(ctx context.Context) error {
m.status.Plugins = offer(c, files, m.pluginStaging(c.Version))
}
}
+ m.logCheck(manifest)
return nil
}
+// logCheck records what the manifest offers compared with this launcher.
+func (m *Manager) logCheck(manifest release.Manifest) {
+ attrs := []any{"manifest_commit", manifest.Commit, "published_at", manifest.PublishedAt}
+ if c := manifest.Launcher; c != nil {
+ attrs = append(attrs, "launcher_installed", m.options.Versions.ClientVersion, "launcher_available", c.Version)
+ }
+ if c := manifest.Plugins; c != nil {
+ attrs = append(attrs, "plugins_installed", m.storeVersion(), "plugins_available", c.Version)
+ }
+ if c := manifest.Server; c != nil {
+ attrs = append(attrs, "server_available", c.Version)
+ }
+ var updates []string
+ if o := m.status.Launcher; o != nil {
+ updates = append(updates, fmt.Sprintf("launcher %s (%d bytes, downloaded=%t)", o.Version, o.Bytes, o.Ready))
+ }
+ if o := m.status.Plugins; o != nil {
+ updates = append(updates, fmt.Sprintf("plugins %s (%d bytes, downloaded=%t)", o.Version, o.Bytes, o.Ready))
+ }
+ if o := m.status.Game; o != nil {
+ updates = append(updates, fmt.Sprintf("game resources %s for %d instance(s)", o.Version, len(m.gamePending)))
+ }
+ if len(updates) == 0 {
+ m.options.Logger.Info("update check: everything is up to date", attrs...)
+ return
+ }
+ m.options.Logger.Info("update check: updates found", append(attrs, "updates", strings.Join(updates, "; "))...)
+}
+
func newer(current, candidate string) bool {
ok, err := release.Newer(current, candidate)
return err == nil && ok
@@ -376,6 +437,7 @@ func (m *Manager) Download(ctx context.Context) error {
var finished int64
for _, j := range jobs {
for _, f := range j.files {
+ m.options.Logger.Info("downloading update file", "version", j.offer.Version, "file", f.Name, "bytes", f.Size)
_, err := release.Download(ctx, m.options.Client, m.manifestURL, f, j.staging, func(_ string, done, _ int64) {
m.mu.Lock()
m.status.Done = finished + done
@@ -389,6 +451,7 @@ func (m *Manager) Download(ctx context.Context) error {
m.mu.Lock()
j.offer.Ready = true
m.mu.Unlock()
+ m.options.Logger.Info("update downloaded and verified", "version", j.offer.Version, "files", len(j.files))
}
return nil
}
@@ -495,8 +558,8 @@ func (m *Manager) replaceStore(c *release.Component) error {
// StoreSources lists the plugin files of the current store set.
func (m *Manager) StoreSources() ([]string, error) {
- m.operation.Lock()
- defer m.operation.Unlock()
+ m.operation <- struct{}{}
+ defer func() { <-m.operation }()
return m.storeSources()
}
@@ -515,7 +578,7 @@ func (m *Manager) storeSources() ([]string, error) {
return nil, fmt.Errorf("invalid stored plugin %q", f.Name)
}
source := filepath.Join(directory, f.Name)
- digest, err := release.HashFile(source)
+ digest, err := util.SHA256File(source)
if err != nil {
return nil, err
}
@@ -588,11 +651,19 @@ func (m *Manager) ensurePlugins(game string) error {
m.mu.Lock()
delete(m.pending, game)
m.mu.Unlock()
- m.options.Logger.Info("plugin set installed", "game", game)
+ m.options.Logger.Info("plugin set installed", "game", game, "plugins", strings.Join(pluginNames(sources), ", "))
}
return err
}
+func pluginNames(sources []string) []string {
+ names := make([]string, len(sources))
+ for i, source := range sources {
+ names[i] = filepath.Base(source)
+ }
+ return names
+}
+
func (m *Manager) installWaiting() {
if !m.begin("installing") {
return
@@ -802,6 +873,11 @@ func (m *Manager) CheckServer(ctx context.Context, client *http.Client, origin s
}
}
slices.Sort(stale)
+ requirement := "none"
+ if fp != nil {
+ requirement = fmt.Sprintf("%s (client %s, update required=%t, game update required=%t)", fp.ID, fp.ClientVersion, fp.RequireClientUpdate, fp.RequireGameUpdate)
+ }
+ m.options.Logger.Info("server compatibility checked", "origin", origin, "server_version", compat.ServerVersion, "game_version", compat.GameVersion, "requirement", requirement, "stale_plugins", strings.Join(stale, ", "))
if len(stale) != 0 {
return fmt.Errorf("Server %s no longer accepts these plugins: %s. Update the plugins in the launcher first", compat.ServerVersion, strings.Join(stale, ", ")) //nolint:staticcheck // ST1005: shown to players
}
@@ -810,8 +886,8 @@ func (m *Manager) CheckServer(ctx context.Context, client *http.Client, origin s
// WithLaunch keeps updates excluded until the prepared game process has started.
func (m *Manager) WithLaunch(ctx context.Context, client *http.Client, game, origin string, launch func() error) error {
- if !m.begin("preparing") {
- return operationBusy()
+ if err := m.acquire(ctx, "preparing"); err != nil {
+ return err
}
defer m.end()
if err := m.CheckServer(ctx, client, origin); err != nil {
diff --git a/go/internal/client/update/selfupdate.go b/go/internal/client/update/selfupdate.go
index 703fce7..42a4c6b 100644
--- a/go/internal/client/update/selfupdate.go
+++ b/go/internal/client/update/selfupdate.go
@@ -1,6 +1,7 @@
package update
import (
+ "bd2server/internal/common/util"
"encoding/json"
"errors"
"fmt"
@@ -146,7 +147,7 @@ func switchLauncher(staging, target, from, to string, keys []release.TrustedKey)
for _, m := range slices.Backward(done) {
current := filepath.Join(target, m.name)
if m.backup != "" {
- if err := commonconfig.ReplaceFile(m.backup, current); err != nil {
+ if err := util.ReplaceFile(m.backup, current); err != nil {
failures = append(failures, fmt.Errorf("restore %s: %w", m.name, err))
}
} else if err := os.Remove(current); err != nil && !errors.Is(err, os.ErrNotExist) {
@@ -195,7 +196,7 @@ func switchLauncher(staging, target, from, to string, keys []release.TrustedKey)
return undo(err)
}
done = append(done, m)
- if err := commonconfig.ReplaceFile(name, current); err != nil {
+ if err := util.ReplaceFile(name, current); err != nil {
_ = os.Remove(name)
return undo(err)
}
diff --git a/go/internal/client/update/selfupdate_test.go b/go/internal/client/update/selfupdate_test.go
index 106bb08..e9b3a43 100644
--- a/go/internal/client/update/selfupdate_test.go
+++ b/go/internal/client/update/selfupdate_test.go
@@ -1,6 +1,7 @@
package update
import (
+ "bd2server/internal/common/util"
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
@@ -67,7 +68,7 @@ func TestRunHelperWaitsForOldLauncherBeforeReplacementResultAndRestart(t *testin
target, staging := filepath.Join(root, "installed"), filepath.Join(root, "staged")
launcherPath := filepath.Join(target, launcherExecutable())
pid, stopLauncher := startWaitingProcess(t, launcherPath)
- oldDigest, err := release.HashFile(launcherPath)
+ oldDigest, err := util.SHA256File(launcherPath)
if err != nil {
t.Fatal(err)
}
@@ -121,7 +122,7 @@ func TestRunHelperWaitsForOldLauncherBeforeReplacementResultAndRestart(t *testin
t.Fatalf("updater finished while the old launcher was still running: %v", helperErr)
case <-time.After(300 * time.Millisecond):
}
- if digest, err := release.HashFile(launcherPath); err != nil || digest != oldDigest {
+ if digest, err := util.SHA256File(launcherPath); err != nil || digest != oldDigest {
t.Fatalf("running launcher was replaced: digest=%s, error=%v", digest, err)
}
assertContent(t, filepath.Join(target, "runtime.dat"), "old runtime")
diff --git a/go/internal/common/config/config.go b/go/internal/common/config/config.go
index 5ecea5f..272f0c3 100644
--- a/go/internal/common/config/config.go
+++ b/go/internal/common/config/config.go
@@ -2,6 +2,7 @@
package config
import (
+ "bd2server/internal/common/util"
"bytes"
"encoding/json"
"errors"
@@ -71,7 +72,7 @@ func Save[T any](path string, value T, options WriteOptions) error {
return err
}
defer func() { _ = os.Remove(temporary) }()
- return ReplaceFile(temporary, path)
+ return util.ReplaceFile(temporary, path)
}
// Ensure publishes defaults atomically and never replaces an existing file.
@@ -111,7 +112,7 @@ func WriteFile(path string, raw []byte) error {
return err
}
defer func() { _ = os.Remove(temporary) }()
- return ReplaceFile(temporary, path)
+ return util.ReplaceFile(temporary, path)
}
func stageBytes(path string, raw []byte, options WriteOptions) (string, error) {
diff --git a/go/internal/common/release/fetch.go b/go/internal/common/release/fetch.go
index 47f26a8..10c1229 100644
--- a/go/internal/common/release/fetch.go
+++ b/go/internal/common/release/fetch.go
@@ -2,6 +2,7 @@ package release
import (
"archive/zip"
+ "bd2server/internal/common/util"
"context"
"crypto/sha256"
"encoding/hex"
@@ -13,8 +14,6 @@ import (
"path/filepath"
"strings"
"time"
-
- commonconfig "bd2server/internal/common/config"
)
const (
@@ -154,7 +153,7 @@ func Download(ctx context.Context, client *http.Client, manifestURL string, file
if written != file.Size || hex.EncodeToString(digest.Sum(nil)) != file.SHA256 {
return "", fmt.Errorf("release: %s failed verification; the download was discarded", file.Name)
}
- if err := commonconfig.ReplaceFile(temporary.Name(), target); err != nil {
+ if err := util.ReplaceFile(temporary.Name(), target); err != nil {
return "", err
}
return target, nil
@@ -166,23 +165,10 @@ func Matches(path string, file File) bool {
if err != nil || !info.Mode().IsRegular() || info.Size() != file.Size {
return false
}
- sum, err := HashFile(path)
+ sum, err := util.SHA256File(path)
return err == nil && sum == file.SHA256
}
-func HashFile(path string) (string, error) {
- f, err := os.Open(path)
- if err != nil {
- return "", err
- }
- defer func() { _ = f.Close() }()
- digest := sha256.New()
- if _, err := io.Copy(digest, f); err != nil {
- return "", err
- }
- return hex.EncodeToString(digest.Sum(nil)), nil
-}
-
// Extract unpacks a verified zip archive into an empty directory, refusing
// entries that would escape it.
func Extract(archive, directory string) error {
diff --git a/go/internal/common/util/file.go b/go/internal/common/util/file.go
new file mode 100644
index 0000000..0e0e715
--- /dev/null
+++ b/go/internal/common/util/file.go
@@ -0,0 +1,21 @@
+package util
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "io"
+ "os"
+)
+
+func SHA256File(path string) (string, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", err
+ }
+ defer func() { _ = f.Close() }()
+ digest := sha256.New()
+ if _, err := io.Copy(digest, f); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(digest.Sum(nil)), nil
+}
diff --git a/go/internal/common/util/random.go b/go/internal/common/util/random.go
new file mode 100644
index 0000000..3d2272f
--- /dev/null
+++ b/go/internal/common/util/random.go
@@ -0,0 +1,42 @@
+package util
+
+import (
+ "crypto/rand"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "math/big"
+)
+
+func RandomUint64N(limit uint64) (uint64, error) {
+ if limit == 0 {
+ return 0, errors.New("util: random upper bound must be positive")
+ }
+ value, err := rand.Int(rand.Reader, new(big.Int).SetUint64(limit))
+ if err != nil {
+ return 0, err
+ }
+ return value.Uint64(), nil
+}
+
+func RandomHex(size int) (string, error) {
+ if size < 0 {
+ return "", errors.New("util: random byte count must not be negative")
+ }
+ raw := make([]byte, size)
+ if _, err := rand.Read(raw); err != nil {
+ return "", err
+ }
+ return hex.EncodeToString(raw), nil
+}
+
+func RandomBase64URL(size int) (string, error) {
+ if size < 0 {
+ return "", errors.New("util: random byte count must not be negative")
+ }
+ raw := make([]byte, size)
+ if _, err := rand.Read(raw); err != nil {
+ return "", err
+ }
+ return base64.RawURLEncoding.EncodeToString(raw), nil
+}
diff --git a/go/internal/common/config/replace_other.go b/go/internal/common/util/replace_other.go
similarity index 93%
rename from go/internal/common/config/replace_other.go
rename to go/internal/common/util/replace_other.go
index 812da3a..481bc4c 100644
--- a/go/internal/common/config/replace_other.go
+++ b/go/internal/common/util/replace_other.go
@@ -1,6 +1,6 @@
//go:build !windows
-package config
+package util
import "os"
diff --git a/go/internal/common/config/replace_windows.go b/go/internal/common/util/replace_windows.go
similarity index 98%
rename from go/internal/common/config/replace_windows.go
rename to go/internal/common/util/replace_windows.go
index 14acbb6..e37e0a0 100644
--- a/go/internal/common/config/replace_windows.go
+++ b/go/internal/common/util/replace_windows.go
@@ -1,6 +1,6 @@
//go:build windows
-package config
+package util
import (
"os"
diff --git a/go/internal/common/util/well512.go b/go/internal/common/util/well512.go
new file mode 100644
index 0000000..d0ca14d
--- /dev/null
+++ b/go/internal/common/util/well512.go
@@ -0,0 +1,31 @@
+package util
+
+type Well512 struct {
+ State [16]uint64
+ Index uint64
+}
+
+func NewWell512(seed uint64) Well512 {
+ r := Well512{}
+ for i := range r.State {
+ r.State[i] = seed + uint64(i)*90
+ }
+ return r
+}
+
+func (r *Well512) Next() uint64 {
+ index := r.Index
+ x, y := r.State[index], r.State[(index+13)&15]
+ b := x ^ y ^ (x << 16) ^ (y << 15)
+ c := r.State[(index+9)&15]
+ c ^= c >> 11
+ x = b ^ c
+ r.State[index] = x
+ // Client IL zero-extends this uint32 mask into the 64-bit state.
+ d := x ^ ((x << 5) & uint64(0xda442d24))
+ index = (index + 15) & 15
+ x = r.State[index]
+ r.State[index] = x ^ b ^ d ^ (x << 2) ^ (b << 18) ^ (c << 28)
+ r.Index = index
+ return r.State[index]
+}
diff --git a/go/internal/server/admin/console.go b/go/internal/server/admin/console.go
index 5e21c7f..bb94b00 100644
--- a/go/internal/server/admin/console.go
+++ b/go/internal/server/admin/console.go
@@ -5,6 +5,7 @@ package admin
import (
"bd2server/internal/common/i18n"
+ "bd2server/internal/common/util"
"context"
"crypto/subtle"
"embed"
@@ -125,7 +126,7 @@ func New(options Options) (*Console, error) {
// externally visible origin of this server. Whoever can read the server's
// output is its operator, so the link needs no other credential.
func (c *Console) IssueSignInLink(base string) (string, error) {
- token, err := randomToken(32)
+ token, err := util.RandomBase64URL(32)
if err != nil {
return "", err
}
@@ -319,7 +320,7 @@ func (c *Console) loginStart(w http.ResponseWriter, r *http.Request) {
fail(w, http.StatusBadRequest, "invalid", "login could not be started")
return
}
- key, err := randomToken(24)
+ key, err := util.RandomBase64URL(24)
if err != nil {
fail(w, http.StatusInternalServerError, "unavailable", "login could not be started")
return
@@ -647,7 +648,7 @@ func (c *Console) sendMail(w http.ResponseWriter, r *http.Request, current sessi
fail(w, http.StatusBadRequest, "invalid_text", "title (1-500) and body (1-5000) are required")
return
}
- identity, err := randomToken(18)
+ identity, err := util.RandomBase64URL(18)
if err != nil {
fail(w, http.StatusInternalServerError, "unavailable", "mail unavailable")
return
diff --git a/go/internal/server/admin/spine_recording_test.go b/go/internal/server/admin/spine_recording_test.go
new file mode 100644
index 0000000..191447e
--- /dev/null
+++ b/go/internal/server/admin/spine_recording_test.go
@@ -0,0 +1,54 @@
+package admin
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "bd2server/internal/server/design/gameconfig"
+)
+
+func TestOwnerCanConfigureRecordingProxyForNextServerStart(t *testing.T) {
+ console, identity, _ := newConsole(t)
+ server := httptest.NewServer(console.Handler())
+ defer server.Close()
+ owner := newBrowser(t, server)
+ if owner.login(identity, "owner") != http.StatusOK {
+ t.Fatal("owner could not open the configuration editor")
+ }
+ status, document := owner.do(http.MethodGet, "/admin/api/config/game", nil, nil)
+ if status != http.StatusOK {
+ t.Fatal("game settings are unavailable")
+ }
+ view := document["view"].(map[string]any)
+ value := view["value"].(map[string]any)
+ value["spine_recording"] = map[string]string{"download_base_url": "https://replay.example.com/recordings"}
+ status, saved := owner.do(http.MethodPut, "/admin/api/config/game", value, map[string]string{"If-Match": view["revision"].(string)})
+ if status != http.StatusOK || saved["pending"] != true {
+ t.Fatalf("recording URL was not saved for restart: status=%d", status)
+ }
+ restarted, err := gameconfig.Document.Load(saved["path"].(string))
+ if err != nil || restarted.SpineRecording.DownloadBaseURL != "https://replay.example.com/recordings" {
+ t.Fatalf("the next server start would lose the owner's recording proxy: %v", err)
+ }
+ for _, invalid := range []string{"javascript:alert(1)", "https://user:password@example.com/replays", "https://example.com/replays?token=secret", "http://example.com/replays"} {
+ value["spine_recording"] = map[string]string{"download_base_url": invalid}
+ status, _ = owner.do(http.MethodPut, "/admin/api/config/game", value, map[string]string{"If-Match": saved["revision"].(string)})
+ if status != http.StatusUnprocessableEntity {
+ t.Fatalf("unsafe recording address replaced a working proxy: status=%d", status)
+ }
+ }
+ restarted, err = gameconfig.Document.Load(saved["path"].(string))
+ if err != nil || restarted.SpineRecording.DownloadBaseURL != "https://replay.example.com/recordings" {
+ t.Fatalf("rejected edit damaged the working recording URL: %v", err)
+ }
+ value["spine_recording"] = map[string]string{"download_base_url": ""}
+ status, saved = owner.do(http.MethodPut, "/admin/api/config/game", value, map[string]string{"If-Match": saved["revision"].(string)})
+ if status != http.StatusOK {
+ t.Fatal("owner could not restore this server as the recording source")
+ }
+ restarted, err = gameconfig.Document.Load(saved["path"].(string))
+ if err != nil || restarted.SpineRecording.DownloadBaseURL != "" {
+ t.Fatalf("clearing the proxy did not persist: %v", err)
+ }
+}
diff --git a/go/internal/server/admin/store.go b/go/internal/server/admin/store.go
index 6d0dc64..5aa6e50 100644
--- a/go/internal/server/admin/store.go
+++ b/go/internal/server/admin/store.go
@@ -1,11 +1,10 @@
package admin
import (
+ "bd2server/internal/common/util"
"context"
- "crypto/rand"
"crypto/sha256"
"database/sql"
- "encoding/base64"
"encoding/json"
"errors"
"fmt"
@@ -80,10 +79,10 @@ func (s *Store) Close() error { return s.db.Close() }
// CreateSession returns a new session token and its CSRF token.
func (s *Store) CreateSession(ctx context.Context, accountID string, role Role) (token, csrf string, err error) {
- if token, err = randomToken(32); err != nil {
+ if token, err = util.RandomBase64URL(32); err != nil {
return "", "", err
}
- if csrf, err = randomToken(24); err != nil {
+ if csrf, err = util.RandomBase64URL(24); err != nil {
return "", "", err
}
now := s.now()
@@ -187,14 +186,6 @@ func (s *Store) RemoveAdministrator(ctx context.Context, accountID string) error
return tx.Commit()
}
-func randomToken(size int) (string, error) {
- b := make([]byte, size)
- if _, err := rand.Read(b); err != nil {
- return "", err
- }
- return base64.RawURLEncoding.EncodeToString(b), nil
-}
-
func digest(token string) []byte {
sum := sha256.Sum256([]byte(token))
return sum[:]
diff --git a/go/internal/server/admin/web/assets/lang/en_us.json b/go/internal/server/admin/web/assets/lang/en_us.json
index 1196ef8..a1610b0 100644
--- a/go/internal/server/admin/web/assets/lang/en_us.json
+++ b/go/internal/server/admin/web/assets/lang/en_us.json
@@ -504,5 +504,9 @@
"console.error.confirming_update": "The previous update is still being checked. Wait until it is confirmed healthy.",
"console.updates.component": "Update content",
"console.updates.component.server": "Server program",
- "console.updates.restarting": "The server is restarting to apply the update. This page reconnects automatically."
+ "console.updates.restarting": "The server is restarting to apply the update. This page reconnects automatically.",
+ "config.game.section.spine_recording.title": "Interaction recording",
+ "config.game.section.spine_recording.help": "Save players’ interactive illustration actions for playback in the game. Restart the server after changing this setting.",
+ "config.game.field.spine_recording.download_base_url.label": "Recording download base URL",
+ "config.game.field.spine_recording.download_base_url.help": "Leave empty to use this server. A custom address must reverse proxy to /client/spine-recordings/ on this server; recording paths and access credentials are appended automatically. Public addresses must use HTTPS."
}
diff --git a/go/internal/server/admin/web/assets/lang/ja_jp.json b/go/internal/server/admin/web/assets/lang/ja_jp.json
index 56b43d6..1954c9f 100644
--- a/go/internal/server/admin/web/assets/lang/ja_jp.json
+++ b/go/internal/server/admin/web/assets/lang/ja_jp.json
@@ -504,5 +504,9 @@
"console.error.confirming_update": "前回の更新の動作確認中です。正常動作の確認が完了するまでお待ちください。",
"console.updates.component": "更新内容",
"console.updates.component.server": "サーバープログラム",
- "console.updates.restarting": "更新を適用するためにサーバーを再起動しています。このページは自動的に再接続します。"
+ "console.updates.restarting": "更新を適用するためにサーバーを再起動しています。このページは自動的に再接続します。",
+ "config.game.section.spine_recording.title": "インタラクション録画",
+ "config.game.section.spine_recording.help": "プレイヤーのイラスト操作を保存し、ゲーム内で再生します。変更後はサーバーを再起動してください。",
+ "config.game.field.spine_recording.download_base_url.label": "録画ダウンロードのベース URL",
+ "config.game.field.spine_recording.download_base_url.help": "空欄の場合はこのサーバーを使用します。独自のアドレスは、このサーバーの /client/spine-recordings/ にリバースプロキシしてください。録画パスとアクセス資格情報は自動で追加されます。外部公開には HTTPS が必要です。"
}
diff --git a/go/internal/server/admin/web/assets/lang/ko_kr.json b/go/internal/server/admin/web/assets/lang/ko_kr.json
index 601bf76..01cbef2 100644
--- a/go/internal/server/admin/web/assets/lang/ko_kr.json
+++ b/go/internal/server/admin/web/assets/lang/ko_kr.json
@@ -504,5 +504,9 @@
"console.error.confirming_update": "이전 업데이트의 정상 작동을 확인하는 중입니다. 확인이 완료될 때까지 기다려 주세요.",
"console.updates.component": "업데이트 내용",
"console.updates.component.server": "서버 프로그램",
- "console.updates.restarting": "업데이트를 적용하기 위해 서버를 다시 시작하는 중입니다. 이 페이지는 자동으로 다시 연결됩니다."
+ "console.updates.restarting": "업데이트를 적용하기 위해 서버를 다시 시작하는 중입니다. 이 페이지는 자동으로 다시 연결됩니다.",
+ "config.game.section.spine_recording.title": "상호작용 녹화",
+ "config.game.section.spine_recording.help": "플레이어의 일러스트 상호작용을 저장하여 게임에서 재생합니다. 설정을 변경한 후 서버를 다시 시작하세요.",
+ "config.game.field.spine_recording.download_base_url.label": "녹화 다운로드 기본 URL",
+ "config.game.field.spine_recording.download_base_url.help": "비워 두면 이 서버를 사용합니다. 사용자 지정 주소는 이 서버의 /client/spine-recordings/ 로 역방향 프록시해야 합니다. 녹화 경로와 접근 자격 정보는 자동으로 추가됩니다. 외부 공개 주소에는 HTTPS가 필요합니다."
}
diff --git a/go/internal/server/admin/web/assets/lang/zh_cn.json b/go/internal/server/admin/web/assets/lang/zh_cn.json
index 0f6a736..838f41f 100644
--- a/go/internal/server/admin/web/assets/lang/zh_cn.json
+++ b/go/internal/server/admin/web/assets/lang/zh_cn.json
@@ -504,5 +504,9 @@
"console.error.confirming_update": "上一次更新仍在进行健康检查,请等待确认完成。",
"console.updates.component": "更新内容",
"console.updates.component.server": "服务端程序",
- "console.updates.restarting": "服务器正在重启以应用更新,本页面会自动重新连接。"
+ "console.updates.restarting": "服务器正在重启以应用更新,本页面会自动重新连接。",
+ "config.game.section.spine_recording.title": "互动录制",
+ "config.game.section.spine_recording.help": "保存玩家的互动立绘操作记录,并供原生客户端回放。修改后重启服务端生效。",
+ "config.game.field.spine_recording.download_base_url.label": "录制下载基础 URL",
+ "config.game.field.spine_recording.download_base_url.help": "留空使用本服地址。自定义地址须反向代理到本服的 /client/spine-recordings/;系统会在其后追加录制路径和访问凭据。公网须使用 HTTPS。"
}
diff --git a/go/internal/server/admin/web/assets/lang/zh_tw.json b/go/internal/server/admin/web/assets/lang/zh_tw.json
index 3555e05..2e55445 100644
--- a/go/internal/server/admin/web/assets/lang/zh_tw.json
+++ b/go/internal/server/admin/web/assets/lang/zh_tw.json
@@ -504,5 +504,9 @@
"console.error.confirming_update": "上次更新仍在進行健康檢查,請等待確認完成。",
"console.updates.component": "更新內容",
"console.updates.component.server": "伺服器程式",
- "console.updates.restarting": "伺服器正在重新啟動以套用更新,本頁面會自動重新連線。"
+ "console.updates.restarting": "伺服器正在重新啟動以套用更新,本頁面會自動重新連線。",
+ "config.game.section.spine_recording.title": "互動錄製",
+ "config.game.section.spine_recording.help": "儲存玩家的互動立繪操作記錄,供原生客戶端重播。修改後重新啟動伺服器生效。",
+ "config.game.field.spine_recording.download_base_url.label": "錄製下載基礎 URL",
+ "config.game.field.spine_recording.download_base_url.help": "留空使用本服位址。自訂位址須反向代理至本服的 /client/spine-recordings/;系統會在其後附加錄製路徑與存取憑證。公網須使用 HTTPS。"
}
diff --git a/go/internal/server/app/castle_battle_integration_test.go b/go/internal/server/app/castle_battle_integration_test.go
new file mode 100644
index 0000000..5ff96f4
--- /dev/null
+++ b/go/internal/server/app/castle_battle_integration_test.go
@@ -0,0 +1,163 @@
+//go:build integration
+
+package app
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/binary"
+ "slices"
+ "testing"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+)
+
+// Current 20261012190548 GameData binds Greed floor 1 to pack3003 deck10001.
+// Its win/no-death/8-turn challenges award material1000 x1, gold30000 and
+// bonus hunting AP5. These expectations come from the read-only GameData query,
+// independently of the castle loader and the runtime reward response.
+func TestCastleTowerBattleRewardsAndChallengesSurviveAccountReopen(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ a := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
+ b := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
+ t.Cleanup(func() { closeNicknamePlayer(t, a.owner); closeNicknamePlayer(t, b.owner) })
+ var blue, deck, character []byte
+ a.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ // ContentOpenTable group1/3003 requires the actual Evil Castle ticket13003.
+ if _, e := p.ownedItems.GrantOnce(ctx, "castle-entry-ticket", []gamedata.BattleReward{{Type: 19, ID: 13003, Count: 1}}); e != nil {
+ t.Fatal(e)
+ }
+ for _, c := range p.worldService.CharacterService().RawAll() {
+ if roster.IsStoryCharacter(c) || roster.IsCharmCharacter(c) {
+ continue
+ }
+ costume, owned := p.collection.CostumeByIndex(c.UseCostume)
+ if !owned || costume.UseChar != c.InvenIndex {
+ continue
+ }
+ hp, e := p.worldService.CharacterService().MaxHealth(ctx, c.InvenIndex)
+ if e != nil {
+ t.Fatal(e)
+ }
+ blue = appScalar(1, 1)
+ blue = append(blue, appScalar(2, c.InvenIndex)...)
+ blue = append(blue, appScalar(3, c.ID)...)
+ blue = append(blue, appScalar(4, hp)...)
+ blue = append(blue, appScalar(6, costume.InvenIndex)...)
+ blue = append(blue, appScalar(7, costume.ID)...)
+ deck = appScalar(1, c.InvenIndex)
+ deck = append(deck, appScalar(2, 0)...)
+ deck = append(deck, appScalar(3, 1)...)
+ character = roster.CharacterWire(c)
+ character, _, e = wire.ReplaceVarint(character, 3, hp)
+ if e != nil {
+ t.Fatal(e)
+ }
+ break
+ }
+ if len(blue) == 0 {
+ t.Fatal("starter player has no owned battle participant")
+ }
+ })
+ a.reopen(t)
+ a.protocol(t, "/PackInGameInfo", trapRequest(1, 3003))
+ beforeGold := a.owner.assembly.wallet.Snapshot(command.Context{}).Gold
+ beforeMaterial := appItemTotals(a.protocol(t, "/ItemInfo", appScalar(1, 2)))[[2]uint64{8, 1000}]
+ bGold := b.owner.assembly.wallet.Snapshot(command.Context{}).Gold
+ bMaterial := appItemTotals(b.protocol(t, "/ItemInfo", appScalar(1, 1)))[[2]uint64{8, 1000}]
+ bonusAP := func(s *trapPlayerScenario) uint64 {
+ t.Helper()
+ var bonus uint64
+ s.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ var e error
+ _, bonus, e = p.huntingService.HuntingAP(ctx)
+ if e != nil {
+ t.Fatal(e)
+ }
+ })
+ return bonus
+ }
+ beforeAP, otherAP := bonusAP(a), bonusAP(b)
+ enter := appScalar(1, 3)
+ enter = append(enter, appScalar(4, 10001)...)
+ enter = append(enter, appScalar(5, 16)...)
+ enter = append(enter, appScalar(9, 1)...)
+ a.protocol(t, "/BattleEnter", enter)
+ common := appScalar(1, 16)
+ common = append(common, appScalar(2, 10001)...)
+ checkpoint := appMessage(1, common)
+ checkpoint = append(checkpoint, appMessage(8, []byte(base64.StdEncoding.EncodeToString(appMessage(3, blue))))...)
+ start := trapRequest(4, 10001)
+ start = wire.AppendBytes(start, 3, deck)
+ start = wire.AppendBytes(start, 5, blue)
+ start = wire.AppendBytes(start, 100, checkpoint)
+ a.protocol(t, "/BattleStart", start)
+ // Reassembly must retain the normal battle's owned party and round evidence.
+ a.reopen(t)
+ end := trapRequest(5, 1)
+ end = wire.AppendBytes(end, 3, character)
+ for _, index := range []uint64{0, 1, 2} {
+ end = wire.AppendVarint(end, 5, index)
+ }
+ settled := a.protocol(t, "/BattleEnd", end)
+ assertAssets := func() {
+ t.Helper()
+ if a.owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold+30000 || appItemTotals(a.protocol(t, "/ItemInfo", appScalar(1, uint64(a.commands+100))))[[2]uint64{8, 1000}] != beforeMaterial+1 || bonusAP(a) != beforeAP+5 {
+ t.Fatal("tower challenges did not credit their authored gold, material and hunting AP exactly once")
+ }
+ }
+ assertAssets()
+ assertTower := func(s *trapPlayerScenario, want bool) {
+ t.Helper()
+ rows := appRows(s.protocol(t, "/EvilCastleTowerInfo", appScalar(1, uint64(s.commands+100))), 1)
+ if !want {
+ if len(rows) != 0 {
+ t.Fatal("unplayed account acquired another player's tower progress")
+ }
+ return
+ }
+ if len(rows) != 1 || appValue(rows[0], 1) != 1 || appValue(rows[0], 3) != 16 {
+ t.Fatal("restored tower floor/mode differs from the played encounter")
+ }
+ var indexes []uint64
+ if e := wire.Walk(rows[0], func(f wire.Field) error {
+ if f.Number == 2 {
+ for raw := f.Value; len(raw) > 0; {
+ value, count := binary.Uvarint(raw)
+ if count <= 0 {
+ return wire.ErrMalformed
+ }
+ indexes = append(indexes, value)
+ raw = raw[count:]
+ }
+ }
+ return nil
+ }); e != nil {
+ t.Fatal(e)
+ }
+ if !slices.Equal(indexes, []uint64{0, 1, 2}) {
+ t.Fatalf("completed tower challenges were lost or fabricated: %v", indexes)
+ }
+ }
+ assertTower(a, true)
+ assertTower(b, false)
+ if replay := a.protocol(t, "/BattleEnd", end); !bytes.Equal(replay, settled) {
+ t.Fatal("battle settlement replay changed its reply")
+ }
+ assertAssets()
+ a.reopen(t)
+ b.reopen(t)
+ assertTower(a, true)
+ assertTower(b, false)
+ assertAssets()
+ if replay := a.protocol(t, "/BattleEnd", end); !bytes.Equal(replay, settled) {
+ t.Fatal("reopened battle receipt changed its reply")
+ }
+ assertAssets()
+ if b.owner.assembly.wallet.Snapshot(command.Context{}).Gold != bGold || appItemTotals(b.protocol(t, "/ItemInfo", appScalar(1, uint64(b.commands+100))))[[2]uint64{8, 1000}] != bMaterial || bonusAP(b) != otherAP {
+ t.Fatal("tower rewards crossed account boundaries")
+ }
+}
diff --git a/go/internal/server/app/design.go b/go/internal/server/app/design.go
index 5a4cd7b..bee4ff2 100644
--- a/go/internal/server/app/design.go
+++ b/go/internal/server/app/design.go
@@ -13,6 +13,15 @@ import (
)
type designCatalog struct {
+ collectionStatistics *gamedata.CollectionStatisticsDesign
+ interaction *gamedata.SpineInteractionDesign
+ community *gamedata.CommunityRewards
+ cafeteria *gamedata.CafeteriaDesign
+ dating *gamedata.DatingDesign
+ castle *gamedata.CastleRewardDesign
+ ib *gamedata.IBDesign
+ roguelike *gamedata.RogueLikeDesign
+ life *gamedata.LifeCatalog
friends gamedata.FriendRules
rooms *gamedata.RoomDesign
roomCommerce *gamedata.RoomCommerceDesign
@@ -34,6 +43,7 @@ type designCatalog struct {
presetDesign *gamedata.PresetDesign
recipeDesign *gamedata.CookingRecipeDesign
randomBoxes *gamedata.RandomBoxDesign
+ resourceItems *gamedata.ResourceItemDesign
itemStacks *gamedata.ItemStackDesign
slotDesign *gamedata.InventorySlotDesign
contentTickets *gamedata.GachaContentTicketDesign
@@ -101,9 +111,45 @@ func loadDesign(c *configuration, seeds *seedCatalog) (*designCatalog, error) {
calendars, gameRules := c.calendars, c.gameRules
d := &designCatalog{source: gamedata.NewSource(gameData, gameDataVersion)}
var err error
+ d.collectionStatistics, err = gamedata.LoadCollectionStatistics(gameData, gameDataVersion)
+ if err != nil {
+ return nil, fmt.Errorf("load collection statistics: %w", err)
+ }
if err := d.loadSharedDesign(c); err != nil {
return nil, err
}
+ d.interaction, err = gamedata.LoadSpineInteractionDesign(gameData, gameDataVersion)
+ if err != nil {
+ return nil, fmt.Errorf("load interaction design: %w", err)
+ }
+ d.community, err = gamedata.LoadCommunityRewards(gameData, gameDataVersion)
+ if err != nil {
+ return nil, fmt.Errorf("load community rewards: %w", err)
+ }
+ d.cafeteria, err = gamedata.LoadCafeteriaDesign(gameData, gameDataVersion)
+ if err != nil {
+ return nil, fmt.Errorf("load cafeteria design: %w", err)
+ }
+ d.dating, err = gamedata.LoadDatingDesign(gameData, gameDataVersion)
+ if err != nil {
+ return nil, fmt.Errorf("load dating design: %w", err)
+ }
+ d.castle, err = gamedata.LoadCastleRewardDesign(gameData, gameDataVersion)
+ if err != nil {
+ return nil, fmt.Errorf("load castle design: %w", err)
+ }
+ d.ib, err = gamedata.LoadIBDesign(gameData, gameDataVersion)
+ if err != nil {
+ return nil, fmt.Errorf("load IB design: %w", err)
+ }
+ d.roguelike, err = gamedata.LoadRogueLikeDesign(gameData, gameDataVersion)
+ if err != nil {
+ return nil, fmt.Errorf("load roguelike design: %w", err)
+ }
+ d.life, err = gamedata.LoadLifeCatalog(gameData, gameDataVersion)
+ if err != nil {
+ return nil, fmt.Errorf("load life design: %w", err)
+ }
d.nicknameTicketID, err = gamedata.LoadNicknameTicketID(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load nickname ticket: %w", err)
@@ -137,6 +183,10 @@ func loadDesign(c *configuration, seeds *seedCatalog) (*designCatalog, error) {
if err != nil {
return nil, fmt.Errorf("load deterministic random-box GameData: %w", err)
}
+ d.resourceItems, err = gamedata.LoadResourceItemDesign(gameData, gameDataVersion)
+ if err != nil {
+ return nil, fmt.Errorf("load resource selection items: %w", err)
+ }
d.itemStacks, err = gamedata.LoadItemStackDesign(gameData, gameDataVersion)
if err != nil {
return nil, fmt.Errorf("load item stack GameData: %w", err)
diff --git a/go/internal/server/app/event_mission_update_integration_test.go b/go/internal/server/app/event_mission_update_integration_test.go
new file mode 100644
index 0000000..3c8d2b2
--- /dev/null
+++ b/go/internal/server/app/event_mission_update_integration_test.go
@@ -0,0 +1,89 @@
+//go:build integration
+
+package app
+
+import (
+ "testing"
+ "time"
+
+ "bd2server/internal/server/domain/events"
+)
+
+// LocalText5700035 asks to change the homescreen. LobbySettingUI saves its
+// slots locally and reports condition39 only through MissionUpdate. Current
+// GameData mission3038 grants four type8/id14 materials and belongs to the
+// third day of EventMissionGroup7001; mission3037 requires equipment upgrades.
+func TestHomescreenMissionPersistsAndPaysOnceWithoutAuthorizingEquipmentProgress(t *testing.T) {
+ g := newMissionGameplay(t)
+ now := time.Now().UTC()
+ g.now = now
+ schedule := events.Schedule{UID: 9001, Type: 4, ID: 7001, Start: now.Add(-72 * time.Hour).UnixMilli(), End: now.Add(24 * time.Hour).UnixMilli()}
+ installCalendar := func() {
+ t.Helper()
+ if err := g.owner.assembly.eventRegistry.Replace([]events.Schedule{schedule}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ installCalendar()
+ update := func(id, value uint64) error {
+ t.Helper()
+ row := append(appScalar(1, 303), appScalar(2, id)...)
+ row = append(row, appScalar(3, value)...)
+ row = append(row, appScalar(4, 7001)...)
+ _, err := g.execute("/MissionUpdate", appMessage(2, row))
+ return err
+ }
+ assertHomescreen := func(want uint64, claimed bool) {
+ t.Helper()
+ for _, row := range appRows(g.call("/EventMissionInfo", nil), 1) {
+ if appValue(row, 1) == 7001 && appValue(row, 3) == 3038 {
+ if appValue(row, 4) != want || (appValue(row, 5) == 1) != claimed {
+ t.Fatalf("homescreen progress not restored: value=%d claimed=%v", appValue(row, 4), appValue(row, 5) == 1)
+ }
+ return
+ }
+ }
+ t.Fatal("third-day homescreen task missing")
+ }
+ claim := append(appScalar(3, 2), appScalar(4, 303)...)
+ claim = append(claim, appScalar(5, 3038)...)
+ claim = append(claim, appScalar(6, 7001)...)
+ before := g.itemCount(8, 14)
+ if _, err := g.execute("/MissionClear", claim); err == nil {
+ t.Fatal("homescreen reward was available before changing the setting")
+ }
+ if err := update(3037, 1); err == nil {
+ t.Fatal("a client report manufactured equipment upgrades")
+ }
+ assertHomescreen(0, false)
+ if err := update(3038, 1); err != nil {
+ t.Fatalf("native local homescreen change rejected: %v", err)
+ }
+ if g.itemCount(8, 14) != before {
+ t.Fatal("reporting a setting change paid its unclaimed reward")
+ }
+ g.reopen()
+ installCalendar()
+ assertHomescreen(1, false)
+ if err := update(3038, 2); err != nil {
+ t.Fatalf("repeated local change beyond completed target rejected: %v", err)
+ }
+ assertHomescreen(1, false)
+ response := g.call("/MissionClear", claim)
+ if missionRewardCount(t, response, 8, 14) != 4 || g.itemCount(8, 14) != before+4 {
+ t.Fatal("homescreen task did not pay its four crafting materials")
+ }
+ g.reopen()
+ installCalendar()
+ assertHomescreen(1, true)
+ if _, err := g.execute("/MissionClear", claim); err == nil {
+ t.Fatal("a new claim paid the same homescreen task twice")
+ }
+ if g.itemCount(8, 14) != before+4 {
+ t.Fatal("reopening or retrying duplicated homescreen materials")
+ }
+ if err := update(3038, 0); err != nil {
+ t.Fatal(err)
+ }
+ assertHomescreen(1, true)
+}
diff --git a/go/internal/server/app/friendship_lifecycle_integration_test.go b/go/internal/server/app/friendship_lifecycle_integration_test.go
new file mode 100644
index 0000000..bb1a00a
--- /dev/null
+++ b/go/internal/server/app/friendship_lifecycle_integration_test.go
@@ -0,0 +1,259 @@
+//go:build integration
+
+package app
+
+import (
+ "bytes"
+ "testing"
+ "time"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/events"
+ "bd2server/internal/server/protocol/wire"
+)
+
+// FriendshipPacket defaults an owned costume to level1 before any counseling.
+// GameData501's first two stories award80 diamonds at levels1 and3; favorite
+// gift7001 gives40EXP, and the first two level thresholds are50 and60.
+func TestFriendshipStoriesFollowEarnedLevelsAndSurviveReentryWithoutDuplicateRewards(t *testing.T) {
+ s := newFriendshipScenario(t)
+ var before, giftIndex uint64
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ if err := p.eventRegistry.Replace(nil); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := p.collection.GrantCostumes(ctx, "friendship-owned-costume", []uint64{501}, p.design.rewardCostumes); err != nil {
+ t.Fatal(err)
+ }
+ items, err := p.ownedItems.GrantOnce(ctx, "friendship-gifts", []gamedata.BattleReward{{Type: 8, ID: 7001, Count: 3}})
+ if err != nil || len(items) != 1 {
+ t.Fatalf("supply gifts: %v", err)
+ }
+ giftIndex = items[0].InvenIndex
+ before = p.wallet.Snapshot(ctx).FreeJewelry
+ })
+ first := friendshipEpisodeRequest(10, 501, 1)
+ response := s.protocol(t, "/FriendshipSpecialEpisodeClear", first)
+ assertFriendshipDiamonds(t, s, before+80)
+ s.reopen(t)
+ if replay := s.protocol(t, "/FriendshipSpecialEpisodeClear", first); !bytes.Equal(response, replay) {
+ t.Fatal("reopening lost the acknowledged story completion")
+ }
+ s.protocol(t, "/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(11, 501, 1))
+ assertFriendshipDiamonds(t, s, before+80)
+ if _, err := s.execute("/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(12, 501, 2)); err == nil {
+ t.Fatal("next story opened without earning its friendship level")
+ }
+ assertFriendshipEpisodes(t, s, 501, 1)
+ request := wire.AppendBytes(wire.AppendVarint(wire.AppendVarint(nil, 1, 13), 2, 501), 3, inventoryItem(giftIndex, 7001, 8, 3))
+ s.protocol(t, "/FriendshipGift", request)
+ s.reopen(t)
+ s.protocol(t, "/FriendshipGift", request)
+ s.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ if level := p.friendshipService.CurrentLevel(501); level != 3 {
+ t.Fatalf("three favorite gifts should earn level3, got%d", level)
+ }
+ for _, item := range p.ownedItems.All(ctx) {
+ if item.InvenIndex == giftIndex && item.Count != 0 {
+ t.Fatal("consumed gifts reappeared after reopening")
+ }
+ }
+ })
+ s.protocol(t, "/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(14, 501, 2))
+ s.reopen(t)
+ assertFriendshipEpisodes(t, s, 501, 1, 2)
+ assertFriendshipDiamonds(t, s, before+160)
+}
+
+// FriendshipStoryPopupUI_StoryItem waives the level requirement only for the
+// scheduled group/episode, but still requires the preceding story to be clear.
+func TestFriendshipEventUnlockIsEpisodeSpecificAndKeepsCompletedStoriesAfterTheEvent(t *testing.T) {
+ s := newFriendshipScenario(t)
+ var before, coinsBefore uint64
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ if _, err := p.collection.GrantCostumes(ctx, "event-friendship-owned-costume", []uint64{60804}, p.design.rewardCostumes); err != nil {
+ t.Fatal(err)
+ }
+ now := time.Now()
+ if err := p.eventRegistry.Replace([]events.Schedule{{UID: 991, Type: 24, ID: 60804, SubID: 2, Start: now.Add(-time.Hour).UnixMilli(), End: now.Add(time.Hour).UnixMilli()}}); err != nil {
+ t.Fatal(err)
+ }
+ before = p.wallet.Snapshot(ctx).FreeJewelry
+ for _, item := range p.ownedItems.All(ctx) {
+ if item.Type == 8 && item.ID == 2068 {
+ coinsBefore += item.Count
+ }
+ }
+ })
+ if _, err := s.execute("/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(20, 60804, 2)); err == nil {
+ t.Fatal("event bypassed the required preceding story")
+ }
+ s.run(t, false, func(_ command.Context, p *playerAssembly) {
+ now := time.Now()
+ if err := p.eventRegistry.Replace([]events.Schedule{{UID: 991, Type: 24, ID: 60804, SubID: 2, Start: now.Add(-time.Hour).UnixMilli(), End: now.Add(time.Hour).UnixMilli()}}); err != nil {
+ t.Fatal(err)
+ }
+ })
+ s.protocol(t, "/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(21, 60804, 1))
+ s.protocol(t, "/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(22, 60804, 2))
+ if _, err := s.execute("/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(23, 60804, 3)); err == nil {
+ t.Fatal("one scheduled episode unlocked an unscheduled episode")
+ }
+ s.reopen(t)
+ s.run(t, false, func(_ command.Context, p *playerAssembly) {
+ if err := p.eventRegistry.Replace(nil); err != nil {
+ t.Fatal(err)
+ }
+ })
+ s.protocol(t, "/FriendshipSpecialEpisodeClear", friendshipEpisodeRequest(24, 60804, 2))
+ assertFriendshipEpisodes(t, s, 60804, 1, 2)
+ assertFriendshipDiamonds(t, s, before+160)
+ s.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ var coins uint64
+ for _, item := range p.ownedItems.All(ctx) {
+ if item.Type == 8 && item.ID == 2068 {
+ coins += item.Count
+ }
+ }
+ if coins != coinsBefore+650 {
+ t.Fatalf("only scheduled episode2 should grant event coins once: got%d want%d", coins, coinsBefore+650)
+ }
+ })
+}
+
+// FriendshipPacket consumes free AP before stacked AP. The per-costume daily
+// limit is separate; an acknowledged consultation must not charge twice.
+func TestFriendshipCounselingConsumesStackedAPOnlyAfterDailyFreeAPAndPersistsTheStory(t *testing.T) {
+ s := newFriendshipScenario(t)
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ if _, err := p.collection.GrantCostumes(ctx, "counseling-costumes", []uint64{501, 801, 1001, 1002}, p.design.rewardCostumes); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := p.eventEconomy.Apply(ctx, "stacked-counseling-supply", nil, []gamedata.Reward{{Type: 72, Count: 1}}); err != nil {
+ t.Fatal(err)
+ }
+ })
+ counsel := func(seq, costume uint64) []byte {
+ return wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, seq), 2, costume), 3, 1)
+ }
+ for i, costume := range []uint64{501, 801, 1001} {
+ s.protocol(t, "/FriendshipCounseling", counsel(uint64(30+i), costume))
+ }
+ s.reopen(t)
+ s.run(t, false, func(_ command.Context, p *playerAssembly) {
+ remaining, err := p.friendshipService.FriendshipAP()
+ if err != nil || remaining != 0 {
+ t.Fatalf("three consultations did not exhaust free AP: remaining%d err%v", remaining, err)
+ }
+ })
+ request := counsel(33, 1002)
+ s.protocol(t, "/FriendshipCounseling", request)
+ s.reopen(t)
+ s.protocol(t, "/FriendshipCounseling", request)
+ s.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ balance, err := p.eventEconomy.CurrencyBalance(ctx, 72)
+ if err != nil || balance != 0 {
+ t.Fatalf("fourth consultation did not spend exactly one stacked AP: balance%d err%v", balance, err)
+ }
+ if level := p.friendshipService.CurrentLevel(1002); level != 2 {
+ t.Fatalf("consultation progress was lost or applied twice: level%d", level)
+ }
+ })
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ if _, err := p.eventEconomy.Apply(ctx, "stacked-counseling-second-supply", nil, []gamedata.Reward{{Type: 72, Count: 1}}); err != nil {
+ t.Fatal(err)
+ }
+ })
+ if _, err := s.execute("/FriendshipCounseling", counsel(34, 1002)); err == nil {
+ t.Fatal("daily costume limit allowed a repeated consultation")
+ }
+ s.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ balance, err := p.eventEconomy.CurrencyBalance(ctx, 72)
+ if err != nil || balance != 1 {
+ t.Fatalf("rejected repeated consultation consumed stacked AP: balance%d err%v", balance, err)
+ }
+ })
+ info := s.protocol(t, "/FriendshipInfo", wire.AppendVarint(nil, 1, 35))
+ var completed bool
+ if err := wire.Walk(info, func(field wire.Field) error {
+ if field.Number == 2 {
+ id, _, err := wire.Varint(field.Value, 1)
+ if err != nil {
+ return err
+ }
+ if id == 1002 {
+ completed = true
+ }
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if !completed {
+ t.Fatal("reentering friendship lost the completed consultation story")
+ }
+}
+
+func newFriendshipScenario(t *testing.T) *trapPlayerScenario {
+ t.Helper()
+ factory, accounts := newIntegrationFactory(t)
+ owner, err := factory.open(accounts[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ s := &trapPlayerScenario{factory: factory, owner: owner, account: accounts[0]}
+ t.Cleanup(func() {
+ if err := s.owner.Close(); err != nil {
+ t.Error(err)
+ }
+ })
+ return s
+}
+
+func friendshipEpisodeRequest(seq, group, id uint64) []byte {
+ return wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, seq), 2, group), 3, id)
+}
+
+func assertFriendshipDiamonds(t *testing.T, s *trapPlayerScenario, want uint64) {
+ t.Helper()
+ s.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ if got := p.wallet.Snapshot(ctx).FreeJewelry; got != want {
+ t.Fatalf("friendship story rewards: diamonds got%d want%d", got, want)
+ }
+ })
+}
+
+func assertFriendshipEpisodes(t *testing.T, s *trapPlayerScenario, group uint64, want ...uint64) {
+ t.Helper()
+ response := s.protocol(t, "/FriendshipSpecialEpisodeInfo", wire.AppendVarint(nil, 1, uint64(100+s.commands)))
+ completed := make(map[uint64]bool)
+ if err := wire.Walk(response, func(field wire.Field) error {
+ if field.Number != 1 {
+ return nil
+ }
+ gotGroup, _, err := wire.Varint(field.Value, 1)
+ if err != nil {
+ return err
+ }
+ id, _, err := wire.Varint(field.Value, 2)
+ if err != nil {
+ return err
+ }
+ if gotGroup != group || completed[id] {
+ t.Fatalf("wrong or repeated story completion: group%d episode%d", gotGroup, id)
+ }
+ completed[id] = true
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if len(completed) != len(want) {
+ t.Fatalf("saved stories got%v want%v", completed, want)
+ }
+ for _, id := range want {
+ if !completed[id] {
+ t.Fatalf("completed story%d lost after reopening", id)
+ }
+ }
+}
diff --git a/go/internal/server/app/guide_pass_integration_test.go b/go/internal/server/app/guide_pass_integration_test.go
new file mode 100644
index 0000000..6156e00
--- /dev/null
+++ b/go/internal/server/app/guide_pass_integration_test.go
@@ -0,0 +1,99 @@
+//go:build integration
+
+package app
+
+import (
+ "encoding/json"
+ "testing"
+
+ "bd2server/internal/server/domain/command"
+)
+
+// PassInfo.GetPassTableList includes schedule-free newbie passes. Current
+// GameData pass76/step1 starts at level1 with box510031, which opens costume3303;
+// level2 requires65 EXP. Homescreen mission3038 contributes10 EXP when claimed.
+func TestGuidePassClaimsAndExperienceSurviveWithoutEventCalendarEntry(t *testing.T) {
+ g := newMissionGameplay(t)
+ passInfo := func() []byte { return g.call("/PassInfo", nil) }
+ assertExperience := func(want uint64) {
+ t.Helper()
+ for _, row := range appRows(passInfo(), 1) {
+ if appValue(row, 1) == 76 {
+ if appValue(row, 2) != want {
+ t.Fatalf("guide pass lost earned EXP: got%d want%d", appValue(row, 2), want)
+ }
+ return
+ }
+ }
+ t.Fatal("native guide pass missing without a seasonal calendar entry")
+ }
+ reward := func(pass, level uint64) []byte {
+ return append(appScalar(3, pass), appScalar(4, level)...)
+ }
+ assertExperience(0)
+ if _, owned := g.owner.assembly.collection.CostumeByID(3303); owned {
+ t.Fatal("guide reward costume already owned before the first guide reward")
+ }
+ if _, err := g.execute("/PassReward", reward(77, 1)); err == nil {
+ t.Fatal("step2 pass rewarded while only step1 was unlocked")
+ }
+ if _, err := g.execute("/PassReward", reward(76, 2)); err == nil {
+ t.Fatal("guide level2 rewarded without its65 EXP")
+ }
+ row := append(appScalar(1, 303), appScalar(2, 3038)...)
+ row = append(row, appScalar(3, 1)...)
+ row = append(row, appScalar(4, 7001)...)
+ g.call("/MissionUpdate", appMessage(2, row))
+ claim := append(appScalar(3, 2), appScalar(4, 303)...)
+ claim = append(claim, appScalar(5, 3038)...)
+ claim = append(claim, appScalar(6, 7001)...)
+ g.call("/MissionClear", claim)
+ assertExperience(10)
+ // Reproduce the previous server's missing derived pass ledger while retaining
+ // the mission reward receipt that independently proves the earned EXP.
+ s := &trapPlayerScenario{owner: g.owner, account: g.account}
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ raw, err := p.gameplayStore.Load(ctx.State, "eventtasks")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var state map[string]json.RawMessage
+ if err := json.Unmarshal(raw, &state); err != nil {
+ t.Fatal(err)
+ }
+ state["Passes"] = json.RawMessage(`{}`)
+ raw, err = json.Marshal(state)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := p.gameplayStore.Save(ctx.State, "eventtasks", raw); err != nil {
+ t.Fatal(err)
+ }
+ })
+ g.reopen()
+ assertExperience(10)
+ assertExperience(10)
+ g.reopen()
+ assertExperience(10)
+ g.call("/PassReward", reward(76, 1))
+ costume, owned := g.owner.assembly.collection.CostumeByID(3303)
+ if !owned || costume.Level != 0 {
+ t.Fatal("guide level1 box failed to grant its initial costume")
+ }
+ g.reopen()
+ if _, err := g.execute("/PassReward", reward(76, 1)); err == nil {
+ t.Fatal("guide reward paid again after player reopen")
+ }
+ if after, owned := g.owner.assembly.collection.CostumeByID(3303); !owned || after.InvenIndex != costume.InvenIndex || after.Level != 0 {
+ t.Fatal("retry duplicated or enhanced the guide reward costume")
+ }
+ claimed := false
+ for _, row := range appRows(passInfo(), 2) {
+ if appValue(row, 1) == 76 && appValue(row, 2) == 1 && appValue(row, 3) == 1 {
+ claimed = true
+ }
+ }
+ if !claimed {
+ t.Fatal("native pass UI cannot restore the claimed level1 marker")
+ }
+}
diff --git a/go/internal/server/app/ib_lifecycle_integration_test.go b/go/internal/server/app/ib_lifecycle_integration_test.go
new file mode 100644
index 0000000..b43331d
--- /dev/null
+++ b/go/internal/server/app/ib_lifecycle_integration_test.go
@@ -0,0 +1,133 @@
+//go:build integration
+
+package app
+
+import (
+ "bytes"
+ "context"
+ "slices"
+ "testing"
+ "time"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/design/schedule"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/runtime/player"
+)
+
+// GameData 20261012190548 LocalText 7900026 promises a single reward per
+// board first clear; 7900084 requires every stage win; 7900122 resets run items.
+// IbStageEndResponse and RewardDBInfoBundle field numbers are from the current
+// extracted Proto.Net classes. This exercises the actual account transaction,
+// economy and HTTP handler chain, including a failed multi-request command.
+func TestIBFirstClearAccountTransactionAndRecovery(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ d := factory.design.ib
+ var seasons []uint64
+ for id := range d.Seasons {
+ seasons = append(seasons, id)
+ }
+ slices.Sort(seasons)
+ season := seasons[0]
+ var board gamedata.IBDungeon
+ for _, id := range d.Seasons[season] {
+ if candidate := d.Dungeons[id]; candidate.Unlock == 0 {
+ board = candidate
+ break
+ }
+ }
+ if board.ID == 0 || board.Reward.Type != 70 {
+ t.Fatal("selected design has no soul-board initial currency reward")
+ }
+ now := time.Now()
+ found := false
+ for n, content := range factory.options.calendars.RegularService.Contents {
+ if content.ID == 9 {
+ factory.options.calendars.RegularService.Contents[n].Current = schedule.Season{ID: season, StartMilliseconds: uint64(now.Add(-time.Hour).UnixMilli()), EndMilliseconds: uint64(now.Add(time.Hour).UnixMilli())}
+ found = true
+ break
+ }
+ }
+ if !found {
+ t.Fatal("calendar has no IB content")
+ }
+ owner, err := factory.open(accounts[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ g := &puzzleGameplay{t: t, factory: factory, account: accounts[0], owner: owner}
+ t.Cleanup(func() {
+ if g.owner != nil {
+ if e := g.owner.Close(); e != nil {
+ t.Error(e)
+ }
+ }
+ })
+ balance := func() uint64 {
+ t.Helper()
+ tx, e := g.owner.repository.BeginCommand(context.Background())
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer func() { _ = tx.Rollback() }()
+ currencies, e := g.owner.assembly.eventEconomy.AdditionalCurrencies(command.Context{State: tx})
+ if e != nil {
+ t.Fatal(e)
+ }
+ return currencies[71]
+ }
+ baseline := balance()
+ g.call("/IbMainInfo", nil)
+ entered := g.call("/IbDungeonEnter", appScalar(2, board.ID))
+ if len(appRows(entered, 2)) == 0 || len(appRows(entered, 3)) == 0 {
+ t.Fatal("handler chain did not create initial board inventory and deck")
+ }
+ for n, stage := range board.Stages {
+ request := append(appScalar(2, board.ID), appScalar(3, stage.ID)...)
+ started := g.call("/IbStageStart", request)
+ g.reopen()
+ if resumed := g.call("/IbStageStart", request); !bytes.Equal(started, resumed) {
+ t.Fatal("account reload changed battle process")
+ }
+ if n+1 < len(board.Stages) {
+ g.call("/IbStageEnd", appScalar(2, 1))
+ continue
+ }
+ failed := g.request("/IbStageEnd", appScalar(2, 1))
+ failed.Requests = append(failed.Requests, player.Request{Path: "/IbDungeonEnter", Body: append(appScalar(1, 9000), appScalar(2, 999999)...)})
+ g.execute(failed, true)
+ g.reopen()
+ if balance() != baseline {
+ t.Fatal("failed batch committed first-clear currency")
+ }
+ main := g.call("/IbMainInfo", nil)
+ play := appRows(main, 1)[0]
+ if appValue(play, 7) != 1 || appValue(play, 2) != stage.ID {
+ t.Fatal("failed batch lost the active final battle")
+ }
+ claim := g.request("/IbStageEnd", appScalar(2, 1))
+ paid := g.execute(claim, false)
+ if appValue(paid, 2) != 1 || appValue(paid, 3) != 1 || balance() != baseline+board.Reward.Count {
+ t.Fatal("first clear did not atomically credit the real account currency")
+ }
+ g.reopen()
+ if retry := g.execute(claim, false); !bytes.Equal(paid, retry) || balance() != baseline+board.Reward.Count {
+ t.Fatal("durable claim retry paid again or changed response")
+ }
+ }
+ if len(appRows(g.call("/IbItemInfo", nil), 1)) != 0 || len(appRows(g.call("/IbDeckInfo", nil), 1)) != 0 {
+ t.Fatal("board completion retained run inventory")
+ }
+ g.call("/IbDungeonEnter", appScalar(2, board.ID))
+ for _, stage := range board.Stages {
+ g.call("/IbStageStart", append(appScalar(2, board.ID), appScalar(3, stage.ID)...))
+ out := g.call("/IbStageEnd", appScalar(2, 1))
+ if appValue(out, 3) != 0 {
+ t.Fatal("rechallenge was marked first clear")
+ }
+ }
+ g.reopen()
+ if balance() != baseline+board.Reward.Count {
+ t.Fatal("rechallenge minted additional first-clear currency")
+ }
+}
diff --git a/go/internal/server/app/map_exploration_integration_test.go b/go/internal/server/app/map_exploration_integration_test.go
index 9fc35ef..4c194e5 100644
--- a/go/internal/server/app/map_exploration_integration_test.go
+++ b/go/internal/server/app/map_exploration_integration_test.go
@@ -4,6 +4,8 @@ package app
import (
"encoding/binary"
+ "slices"
+ "strconv"
"testing"
"bd2server/internal/server/design/gamedata"
@@ -12,6 +14,93 @@ import (
"bd2server/internal/server/protocol/wire"
)
+// MapPacket and MapFogController use eight ordered hexadecimal row masks;
+// PackInGameInfo clears the local cache before restoring field 10.
+func TestMapFogKeepsRevealedCellsAcrossAreaChangesAndAccountReopen(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ players := make([]*trapPlayerScenario, 2)
+ for i, account := range accounts {
+ s := &trapPlayerScenario{factory: factory, account: account, owner: openNicknamePlayer(t, factory, account)}
+ players[i] = s
+ t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ if rule := p.design.world.Story.Packs[5].Open; rule != nil && rule.TicketID != 0 {
+ if _, err := p.ownedItems.GrantOnce(ctx, "fog-pack-ticket", []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ })
+ }
+ a, b := players[0], players[1]
+ reveal := func(s *trapPlayerScenario, pack, mapID uint64, rows ...string) {
+ t.Helper()
+ request := wire.AppendVarint(trapRequest(uint64(s.commands+1), pack), 3, mapID)
+ for _, row := range rows {
+ request = wire.AppendString(request, 4, row)
+ }
+ s.protocol(t, "/ActiveMap", request)
+ }
+ assertCells := func(s *trapPlayerScenario, pack uint64, expected map[uint64][]int) {
+ t.Helper()
+ entry := s.protocol(t, "/PackInGameInfo", trapRequest(uint64(s.commands+1), pack))
+ maps := appRows(entry, 10)
+ if len(maps) != len(expected) {
+ t.Fatalf("field entry restored %d explored maps, want %d", len(maps), len(expected))
+ }
+ seen := map[uint64]bool{}
+ for _, m := range maps {
+ id := appValue(m, 1)
+ wanted, exists := expected[id]
+ if !exists || seen[id] {
+ t.Fatalf("field entry restored unrelated or duplicated map %d", id)
+ }
+ seen[id] = true
+ rows := appRows(m, 2)
+ if len(rows) != 8 {
+ t.Fatal("native fog renderer requires all eight rows, including empty rows")
+ }
+ var cells []int
+ for r, text := range rows {
+ var mask uint64
+ if len(text) != 0 {
+ var err error
+ mask, err = strconv.ParseUint(string(text), 16, 8)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ for column := range 8 {
+ if mask&(1<= season.StartMilliseconds && now < season.EndMilliseconds {
+ return ib.Period{Season: season.ID, Regular: regular, Open: !season.Error}, nil
+ }
+ }
+ return ib.Period{Season: content.Current.ID, Regular: regular}, nil
+ }
+ return ib.Period{}, fmt.Errorf("ib: missing content calendar")
+ }})
+ return err
+}
diff --git a/go/internal/server/app/player_interaction.go b/go/internal/server/app/player_interaction.go
new file mode 100644
index 0000000..3c77ad9
--- /dev/null
+++ b/go/internal/server/app/player_interaction.go
@@ -0,0 +1,37 @@
+package app
+
+import "bd2server/internal/server/domain/command"
+
+func (p *playerAssembly) interactionAvailable(ctx command.Context, group uint64) (bool, error) {
+ for _, access := range p.design.interaction.Access[group] {
+ if access.Prestige != 0 {
+ for _, item := range p.ownedItems.All(ctx) {
+ if item.Type == 45 && item.ID == access.Prestige && item.Count != 0 {
+ return true, nil
+ }
+ }
+ continue
+ }
+ if access.Costume != 0 {
+ if _, owned := p.collection.CostumeByID(access.Costume); owned {
+ return true, nil
+ }
+ continue
+ }
+ switch access.Provide {
+ case 0:
+ return true, nil
+ case 1:
+ if p.worldService.PackAvailable(ctx, access.Pack) {
+ return true, nil
+ }
+ case 2:
+ for _, item := range p.ownedItems.All(ctx) {
+ if item.Type == 25 && item.ID == access.Item && item.Count != 0 {
+ return true, nil
+ }
+ }
+ }
+ }
+ return false, nil
+}
diff --git a/go/internal/server/app/player_optional_gameplay.go b/go/internal/server/app/player_optional_gameplay.go
new file mode 100644
index 0000000..a50f481
--- /dev/null
+++ b/go/internal/server/app/player_optional_gameplay.go
@@ -0,0 +1,133 @@
+package app
+
+import (
+ "encoding/json"
+ "fmt"
+ "slices"
+ "time"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/design/schedule"
+ "bd2server/internal/server/domain/battle/castle"
+ "bd2server/internal/server/domain/cafeteria"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/dating"
+ "bd2server/internal/server/domain/life"
+ "bd2server/internal/server/domain/roster/deck"
+)
+
+func (p *playerAssembly) optionalGameplay(ctx command.Context) error {
+ var err error
+ p.lifeService, err = life.Open(ctx, p.design.life, life.Options{ValidateAvatar: func(ctx command.Context, raw []byte) error {
+ if p.avatarService == nil {
+ return fmt.Errorf("life: avatar service unavailable")
+ }
+ return p.avatarService.ValidateAppearance(ctx, raw)
+ }})
+ if err != nil {
+ return fmt.Errorf("open life: %w", err)
+ }
+ p.eventEconomy.AttachLife(p.lifeService)
+ if err := p.eventEconomy.AttachDatingAP(p.design.dating.Default.V(5)); err != nil {
+ return err
+ }
+ p.datingService, err = dating.Open(ctx, p.gameplayStore, p.design.dating, p.eventEconomy)
+ if err != nil {
+ return fmt.Errorf("open dating: %w", err)
+ }
+ p.cafeteriaService, err = cafeteria.Open(ctx, p.gameplayStore, p.design.cafeteria, p.eventEconomy)
+ if err != nil {
+ return fmt.Errorf("open cafeteria: %w", err)
+ }
+ p.datingService.SetResetSeconds(p.design.eventAPReset.ResetSeconds)
+ p.cafeteriaService.SetResetSeconds(p.design.eventAPReset.ResetSeconds)
+ p.cafeteriaService.AttachOwnedCostumes(func() []uint64 {
+ var ids []uint64
+ for _, costume := range p.collection.Costumes() {
+ ids = append(ids, costume.ID)
+ }
+ return ids
+ })
+ p.cafeteriaService.AttachDatingHasEpisode(p.datingService.HasEpisode)
+ p.datingService.AttachFirstMeeting(p.cafeteriaService.CanMeet)
+ p.castleService = castle.NewService(p.design.castle)
+ p.castleService.AttachTotalWarTextCheck(p.checkProfileText)
+ if err := p.castleService.AttachTotalWarRuntime(p.worldService.CharacterService(), p.collection, p.ownedEquipment, p.wallet); err != nil {
+ return err
+ }
+ if err := p.login.AttachTotalWarSlots(p.castleService.TotalWarPresetSlotCount); err != nil {
+ return err
+ }
+ p.castleService.AttachTotalWarCompletion(func(ctx command.Context, identity string, score uint64, costumes []uint64) error {
+ owner, err := p.ProfileOwner(ctx)
+ if err != nil {
+ return err
+ }
+ payload, err := json.Marshal(deck.PopularityPublication{CompletedAt: uint64(time.Now().UnixMilli()), Score: score, OwnerIndex: owner, TotalWarCostumes: append([]uint64(nil), costumes...)})
+ if err != nil {
+ return err
+ }
+ return ctx.Publish(command.Event{ID: "totalwar:" + identity, Topic: deck.PopularityTopic, Payload: payload})
+ })
+ p.castleService.AttachCurrentPack(p.worldService.CurrentPackID)
+ p.castleService.AttachEvidence(p.battleService.SettlementEvidence)
+ p.castleService.AttachRewards(func(ctx command.Context, identity string, rewards []gamedata.Reward) ([]byte, error) {
+ return p.eventEconomy.Apply(ctx, identity, nil, rewards)
+ })
+ p.castleService.AttachSeasonSettlement(func(id uint64) bool {
+ calendar := p.options.calendars.RegularService
+ if calendar == nil {
+ return false
+ }
+ now := uint64(time.Now().UnixMilli())
+ for _, content := range calendar.Contents {
+ if content.ID != 2 {
+ continue
+ }
+ for _, season := range []schedule.Season{content.Current, content.Next} {
+ if season.ID == id {
+ return !season.Error && now >= season.EndMilliseconds+calendar.CalculateMilliseconds
+ }
+ }
+ return id < content.Current.ID
+ }
+ return false
+ })
+ p.castleService.AttachPeriod(func(command.Context) (uint64, bool, error) {
+ if p.options.calendars.RegularService == nil {
+ return 0, false, fmt.Errorf("castle: missing regular calendar")
+ }
+ now := uint64(time.Now().UnixMilli())
+ for _, content := range p.options.calendars.RegularService.Contents {
+ if content.ID != 2 {
+ continue
+ }
+ for _, season := range []schedule.Season{content.Current, content.Next} {
+ if now >= season.StartMilliseconds && now < season.EndMilliseconds && !season.Error {
+ return season.ID, true, nil
+ }
+ }
+ return content.Current.ID, false, nil
+ }
+ return 0, false, fmt.Errorf("castle: missing season")
+ })
+ p.castleService.AttachTotalWarValidation(func(ctx command.Context, participants []castle.Participant) error {
+ for _, participant := range participants {
+ costume, owned := p.collection.CostumeByIndex(participant.CostumeIndex)
+ if !owned || costume.ID != participant.CostumeID {
+ return fmt.Errorf("castle: total war costume unavailable")
+ }
+ character, owned := p.worldService.CharacterService().Find(ctx, participant.CharacterIndex)
+ if !owned || character.ID != participant.CharacterID {
+ return fmt.Errorf("castle: total war character unavailable")
+ }
+ definition, found := p.design.regularGacha.Character(costume.ID)
+ if !found || definition.ID != character.ID && !slices.Contains(definition.GrowthCharacterIDs, character.ID) {
+ return fmt.Errorf("castle: costume belongs to a different character")
+ }
+ }
+ return nil
+ })
+ p.battleService.AttachEventBattle(p.castleService)
+ return nil
+}
diff --git a/go/internal/server/app/player_roguelike.go b/go/internal/server/app/player_roguelike.go
new file mode 100644
index 0000000..a0173b7
--- /dev/null
+++ b/go/internal/server/app/player_roguelike.go
@@ -0,0 +1,172 @@
+package app
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/design/schedule"
+ "bd2server/internal/server/domain/battle/roguelike"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/outbox"
+
+ "context"
+ "encoding/json"
+ "fmt"
+
+ "time"
+)
+
+func (s *sharedRuntime) consumeRogueRanking(ctx context.Context, event outbox.Pending) error {
+ var p roguelike.RankPublication
+ if e := json.Unmarshal(event.Envelope.Event.Payload, &p); e != nil {
+ return e
+ }
+ if p.Account != event.Envelope.Source {
+ return fmt.Errorf("roguelike: ranking source mismatch")
+ }
+ return s.rogueRanks.Publish(ctx, p)
+}
+func (p *playerAssembly) rogueLike(ctx command.Context) error {
+ owner, e := p.ProfileOwner(ctx)
+ if e != nil {
+ return e
+ }
+ service, e := roguelike.Open(p.gameplayStore, p.design.roguelike, roguelike.Options{Access: func(ctx command.Context) error {
+ rule := p.design.roguelike.Open
+ xp, e := p.missionService.AchievementExperience()
+ if e != nil {
+ return e
+ }
+ if p.design.levelDesign.Level(xp) < rule.SquadLevel {
+ return fmt.Errorf("roguelike: squad level locked")
+ }
+ if rule.TicketID > 0 {
+ found := false
+ for _, i := range p.ownedItems.All(ctx) {
+ if i.Type == 19 && i.ID == rule.TicketID && i.Count > 0 {
+ found = true
+ }
+ }
+ if !found {
+ return fmt.Errorf("roguelike: content locked")
+ }
+ }
+ return nil
+ }, Economy: p.eventEconomy, Owner: owner, Evidence: p.battleService.SettlementEvidence,
+ CostumeOwned: func(id uint64) bool {
+ _, owned := p.collection.CostumeByID(id)
+ return owned
+ },
+ SeasonSettled: func(id uint64) bool {
+ calendar := p.options.calendars.RegularService
+ if calendar == nil {
+ return false
+ }
+ now := uint64(time.Now().UnixMilli())
+ for _, content := range calendar.Contents {
+ if content.ID != 5 {
+ continue
+ }
+ for _, season := range []schedule.Season{content.Current, content.Next} {
+ if season.ID == id {
+ return !season.Error && now >= season.EndMilliseconds+calendar.CalculateMilliseconds
+ }
+ }
+ return id < content.Current.ID
+ }
+ return false
+ },
+ Period: func(command.Context) (roguelike.Period, error) {
+ calendar := p.options.calendars.RegularService
+ if calendar == nil {
+ return roguelike.Period{}, fmt.Errorf("roguelike: calendar unavailable")
+ }
+ now := uint64(time.Now().UnixMilli())
+ var regular uint64
+ for _, r := range calendar.Regular {
+ if r.ContentID == 5 {
+ regular = r.Season
+ }
+ }
+ for _, c := range calendar.Contents {
+ if c.ID != 5 {
+ continue
+ }
+ for _, s := range []schedule.Season{c.Current, c.Next} {
+ if now >= s.StartMilliseconds && now < s.EndMilliseconds && !s.Error {
+ return roguelike.Period{Season: s.ID, Regular: regular, Active: true}, nil
+ }
+ }
+ return roguelike.Period{Season: c.Current.ID, Regular: regular}, nil
+ }
+ return roguelike.Period{}, fmt.Errorf("roguelike: missing schedule")
+ },
+ Tickets: func(ctx command.Context, key string, count uint64) error {
+ free, e := p.eventEconomy.CurrencyBalance(ctx, 35)
+ if e != nil {
+ return e
+ }
+ var costs []gamedata.Reward
+ if use := min(free, count); use > 0 {
+ costs = append(costs, gamedata.Reward{Type: 35, Count: use})
+ count -= use
+ }
+ if count > 0 {
+ costs = append(costs, gamedata.Reward{Type: 38, Count: count})
+ }
+ _, e = p.eventEconomy.Apply(ctx, key+":tickets", costs, nil)
+ return e
+ },
+ Health: func(ctx command.Context, c gamedata.RogueCostume, growth float64) (uint64, error) {
+ contributions, e := p.pictorialService.Contributions(ctx)
+ if e != nil {
+ return 0, e
+ }
+ awake, e := p.charAwakeService.Contributions(ctx, roster.Character{ID: c.Character})
+ if e != nil {
+ return 0, e
+ }
+ contributions = append(contributions, awake...)
+ contributions = append(contributions, gamedata.StatContribution{Stat: gamedata.StatHealth, Percent: growth})
+ hp := gamedata.AggregateStats(gamedata.BaseStats{Health: float64(c.Health)}, contributions).Health
+ return uint64(hp), nil
+ },
+ Ranking: p.rogueRanking(),
+ Publish: func(ctx command.Context, season, score, damage, version uint64) error {
+ profile, e := p.PublicProfile(ctx, owner)
+ if e != nil {
+ return e
+ }
+ xp, e := p.missionService.AchievementExperience()
+ if e != nil {
+ return e
+ }
+ raw := wire.AppendString(nil, 2, profile.UserID)
+ raw = wire.AppendVarint(raw, 3, xp)
+ raw = wire.AppendVarint(raw, 4, profile.PortraitCostumeID)
+ raw = wire.AppendVarint(raw, 5, profile.PortraitDesignID)
+ raw = wire.AppendVarint(raw, 9, profile.TitleID)
+ if len(profile.GuildBase) > 0 {
+ raw = wire.AppendBytes(raw, 6, profile.GuildBase)
+ }
+ payload, e := json.Marshal(roguelike.RankPublication{Account: ctx.AccountID, Season: season, Version: version, Entry: roguelike.RankEntry{Owner: owner, Score: score, Damage: damage, Profile: raw}})
+ if e != nil {
+ return e
+ }
+ return ctx.Publish(command.Event{ID: fmt.Sprintf("roguelike-rank:%d:%d", season, version), Topic: "roguelike.ranking", Payload: payload})
+ },
+ })
+ if e != nil {
+ return e
+ }
+ p.rogueLikeService = service
+ p.battleService.AttachEventBattle(service)
+ return nil
+}
+
+func (p *playerAssembly) rogueRanking() roguelike.Ranking {
+ if p.shared == nil {
+ return nil
+ }
+ return p.shared.rogueRanks
+}
diff --git a/go/internal/server/app/player_session.go b/go/internal/server/app/player_session.go
index 273bdce..3ab8a12 100644
--- a/go/internal/server/app/player_session.go
+++ b/go/internal/server/app/player_session.go
@@ -8,6 +8,7 @@ import (
"bd2server/internal/server/domain/events"
"bd2server/internal/server/domain/notice"
"bd2server/internal/server/domain/profile"
+ "bd2server/internal/server/domain/roster"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/gateway/session"
"bd2server/internal/server/protocol/defaults"
@@ -26,6 +27,7 @@ func (p *playerAssembly) session(ctx command.Context) error {
return err
}
p.monsterHuntService.AttachRanking(owner, p.shared.huntRanks)
+ p.castleService.AttachRanking(owner, p.shared.castleRanks)
}
if err := p.nickname(ctx); err != nil {
return err
@@ -47,6 +49,17 @@ func (p *playerAssembly) session(ctx command.Context) error {
return fmt.Errorf("restore recorded achievement history: %w", err)
}
p.handlers = []session.Handler{
+ p.lifeService,
+ p.cafeteriaService,
+ p.datingService,
+ p.castleService,
+ p.ibService,
+ p.rogueLikeService,
+ notice.CommunityService{Store: p.gameplayStore, Design: p.design.community, Board: p.options.notices, Economy: p.eventEconomy},
+ roster.InteractionService{Store: p.gameplayStore, Design: p.design.interaction, Authorize: p.interactionAvailable, Grant: func(ctx command.Context, key string, rewards []gamedata.Reward) ([]byte, error) {
+ return p.eventEconomy.Apply(ctx, key, nil, rewards)
+ }},
+ p.interactionRecords(),
p.chatService,
p.nicknameService,
p.avatarService,
diff --git a/go/internal/server/app/player_system.go b/go/internal/server/app/player_system.go
index 71151c2..674b553 100644
--- a/go/internal/server/app/player_system.go
+++ b/go/internal/server/app/player_system.go
@@ -40,6 +40,13 @@ func executePlayerSystem(ctx context.Context, registry *playerRegistry, account
func (instance *playerInstance) executeSystem(ctx command.Context, tx *accountstate.CommandStore, request *player.SystemRequest) ([]byte, error) {
p := instance.assembly
+ if request.Kind == player.ReadSpineRecording {
+ var input spineRecordingDownload
+ if err := json.Unmarshal(request.Body, &input); err != nil {
+ return nil, err
+ }
+ return p.interactionRecords().LoadRecordData(ctx, input.ID, input.Token)
+ }
if request.Kind == player.StoryCheckpoint {
var input world.StoryCheckpointRequest
if err := json.Unmarshal(request.Body, &input); err != nil {
diff --git a/go/internal/server/app/player_text.go b/go/internal/server/app/player_text.go
index 4830da7..862233c 100644
--- a/go/internal/server/app/player_text.go
+++ b/go/internal/server/app/player_text.go
@@ -30,24 +30,27 @@ type textField struct {
}
var playerTextFields = map[string][]textField{
- "/UserNicknameChange": {{"nickname", 74, []int{2}}},
- "/UserGreetingChange": {{"greeting", 219, []int{2}}},
- "/MasterTitleInfoUpdate": {{"master_title", 592, []int{2}}},
- "/PresetSave": {{"preset_name", 179, []int{2, 1}}},
- "/PresetInfoChange": {{"preset_name", 278, []int{2}}},
- "/EquipPresetSave": {{"equipment_preset_name", 254, []int{4}}},
- "/EquipPresetNameChange": {{"equipment_preset_name", 259, []int{4}}},
- "/EquipMarkSet": {{"equipment_mark", 396, []int{3}}},
- "/MonsterHuntPresetSave": {{"monster_hunt_preset_name", 406, []int{2, 1}}},
- "/MonsterHuntPresetInfoChange": {{"monster_hunt_preset_name", 0, []int{2}}},
- "/GuildRaidPresetSave": {{"guild_raid_preset_name", 404, []int{2, 1}}},
- "/GuildRaidPresetInfoChange": {{"guild_raid_preset_name", 0, []int{2}}},
- "/ColosseumPresetSave": {{"colosseum_preset_name", 494, []int{2, 1}}},
- "/ColosseumPresetInfoChange": {{"colosseum_preset_name", 497, []int{2}}},
- "/GuildCreate": {{"guild_name", 296, []int{2}}, {"guild_message", 296, []int{5}}},
- "/GuildInfoEdit": {{"guild_message", 305, []int{4}}},
- "/GuildNameChange": {{"guild_name", 570, []int{2}}},
- "/GuildNoticeUpdate": {{"guild_notice", 382, []int{2}}},
+ "/UserNicknameChange": {{"nickname", 74, []int{2}}},
+ "/UserGreetingChange": {{"greeting", 219, []int{2}}},
+ "/MasterTitleInfoUpdate": {{"master_title", 592, []int{2}}},
+ "/PresetSave": {{"preset_name", 179, []int{2, 1}}},
+ "/PresetInfoChange": {{"preset_name", 278, []int{2}}},
+ "/EquipPresetSave": {{"equipment_preset_name", 254, []int{4}}},
+ "/EquipPresetNameChange": {{"equipment_preset_name", 259, []int{4}}},
+ "/EquipMarkSet": {{"equipment_mark", 396, []int{3}}},
+ "/MonsterHuntPresetSave": {{"monster_hunt_preset_name", 406, []int{2, 1}}},
+ "/MonsterHuntPresetInfoChange": {{"monster_hunt_preset_name", 0, []int{2}}},
+ "/GuildRaidPresetSave": {{"guild_raid_preset_name", 404, []int{2, 1}}},
+ "/GuildRaidPresetInfoChange": {{"guild_raid_preset_name", 0, []int{2}}},
+ "/ColosseumPresetSave": {{"colosseum_preset_name", 494, []int{2, 1}}},
+ "/ColosseumPresetInfoChange": {{"colosseum_preset_name", 497, []int{2}}},
+ "/TotalWarDeckPresetSave": {{"total_war_preset_name", 240, []int{2, 2}}},
+ "/TotalWarPresetInfoChange": {{"total_war_preset_name", 0, []int{2}}},
+ "/GuildCreate": {{"guild_name", 296, []int{2}}, {"guild_message", 296, []int{5}}},
+ "/GuildInfoEdit": {{"guild_message", 305, []int{4}}},
+ "/GuildNameChange": {{"guild_name", 570, []int{2}}},
+ "/GuildNoticeUpdate": {{"guild_notice", 382, []int{2}}},
+ "/SpineInteractionRecordNameUpdate": {{"spine_record_name", 576, []int{3}}},
}
func hasPlayerText(requests []player.Request) bool {
diff --git a/go/internal/server/app/player_world_roster.go b/go/internal/server/app/player_world_roster.go
index 0349186..b4fe5c1 100644
--- a/go/internal/server/app/player_world_roster.go
+++ b/go/internal/server/app/player_world_roster.go
@@ -68,6 +68,9 @@ func (p *playerAssembly) worldRoster(ctx command.Context) error {
}
p.gachaService.AttachInventory(p.ownedItems)
p.gachaService.AttachEquipmentGacha(p.design.equipmentGacha, p.ownedEquipment)
+ if err := p.gachaService.AttachStatistics(p.design.collectionStatistics); err != nil {
+ return err
+ }
p.gachaService.AttachDrawMission(func(ctx command.Context, count uint64) error {
return p.missionService.RecordEvent(ctx, missions.ConditionGachaBuy, 0, count, p.worldService.MissionsUnlocked)
})
@@ -174,7 +177,7 @@ func (p *playerAssembly) worldRoster(ctx command.Context) error {
if err != nil {
return err
}
- p.friendshipService, err = roster.NewFriendshipService(&p.design.friendshipDesign, p.design.charAwakeDesign, p.design.costumePotentialDesign, p.collection, p.ownedItems, p.wallet)
+ p.friendshipService, err = roster.NewFriendshipService(&p.design.friendshipDesign, p.design.charAwakeDesign, p.design.costumePotentialDesign, p.collection, p.ownedItems)
if err != nil {
return fmt.Errorf("load friendship state: %w", err)
}
diff --git a/go/internal/server/app/prestige_illustration_integration_test.go b/go/internal/server/app/prestige_illustration_integration_test.go
new file mode 100644
index 0000000..c8daea0
--- /dev/null
+++ b/go/internal/server/app/prestige_illustration_integration_test.go
@@ -0,0 +1,126 @@
+//go:build integration
+
+package app
+
+import (
+ "bytes"
+ "context"
+ "testing"
+ "time"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+)
+
+// Current GameData links prestige 65193 to lobby illustration274 and prestige
+// 3892 to135. Ordinary illustration32 is a dating reward, not a costume grant.
+// Native MenuUI builds its interaction button from ItemInfo's Type25 rows.
+func TestOwnedPrestigeUnlocksInteractionOnLoginAndWhenClaimed(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
+ var sourceTime uint64
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ p.ownedItems.AttachPrestigeIllustrations(nil)
+ items, err := p.ownedItems.GrantOnce(ctx, "historical-prestige", []gamedata.BattleReward{{Type: 45, ID: 65193, Count: 1}})
+ if err != nil || len(items) != 1 {
+ t.Fatalf("seed historical external ownership: %v", err)
+ }
+ sourceTime = items[0].TimeValue
+ if _, err := p.collection.GrantCostumes(ctx, "ordinary-costume", []uint64{3303}, p.design.rewardCostumes); err != nil {
+ t.Fatal(err)
+ }
+ if err := p.mailService.EnqueueCompensation(ctx, "new-prestige", "Interaction test", "Claim a new prestige skin", []gamedata.Reward{{Type: 45, ID: 3892, Count: 1}}, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ })
+ closeNicknamePlayer(t, s.owner)
+ registry := newPlayerRegistry(factory, time.Minute)
+ t.Cleanup(func() {
+ if err := registry.Close(context.Background()); err != nil {
+ t.Error(err)
+ }
+ })
+ a, b := friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
+ find := func(rows [][]byte, typ, id uint64) []byte {
+ t.Helper()
+ var result []byte
+ for _, row := range rows {
+ if appValue(row, 3) == typ && appValue(row, 2) == id {
+ if result != nil {
+ t.Fatalf("duplicate native inventory row for %d/%d", typ, id)
+ }
+ result = row
+ }
+ }
+ return result
+ }
+ items := appRows(a.send("/ItemInfo", nil, 21, 0), 1)
+ illustration := find(items, 25, 274)
+ if illustration == nil || appValue(illustration, 1) == 0 || appValue(illustration, 4) != 1 || appValue(illustration, 6) != sourceTime {
+ t.Fatal("historical prestige ownership did not restore a selectable interactive illustration")
+ }
+ if find(items, 25, 32) != nil || find(items, 25, 135) != nil {
+ t.Fatal("login bypassed dating progression or unlocked an unclaimed prestige skin")
+ }
+ if find(appRows(b.send("/ItemInfo", nil, 21, 0), 1), 25, 274) != nil {
+ t.Fatal("another player's prestige unlocked this player's interaction entry")
+ }
+ var mailID uint64
+ for _, row := range appRows(a.send("/MailInfo", nil, 131, 0), 1) {
+ title, _, err := wire.Bytes(row, 5)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if string(title) == "Interaction test" {
+ mailID = appValue(row, 1)
+ }
+ }
+ if mailID == 0 {
+ t.Fatal("new prestige claim mail is missing")
+ }
+ claim := a.send("/MailOpen", appScalar(2, mailID), 132, 0)
+ bundles := appRows(claim, 1)
+ if len(bundles) != 1 {
+ t.Fatal("mail claim did not return the native reward bundle")
+ }
+ granted := appRows(bundles[0], 1)
+ if find(granted, 45, 3892) == nil || find(granted, 25, 135) == nil {
+ t.Fatal("claiming prestige did not unlock interaction in the current client session")
+ }
+ a.seq--
+ if retry := a.send("/MailOpen", appScalar(2, mailID), 132, 0); !bytes.Equal(retry, claim) {
+ t.Fatal("claim retry changed the associated illustration update")
+ }
+ if err := registry.Close(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ registry = newPlayerRegistry(factory, time.Minute)
+ a = friendHTTPLogin(t, registry, accounts[0])
+ items = appRows(a.send("/ItemInfo", nil, 21, 0), 1)
+ if !bytes.Equal(find(items, 25, 274), illustration) || find(items, 25, 135) == nil || find(items, 25, 32) != nil {
+ t.Fatal("relogin changed illustration identity, lost a claimed interaction, or bypassed dating")
+ }
+ a.send("/MailOpen", appScalar(2, mailID), 132, 0)
+ if rows := appRows(a.send("/ItemInfo", nil, 21, 0), 1); !bytes.Equal(find(rows, 25, 135), find(items, 25, 135)) {
+ t.Fatal("reopening claimed mail duplicated the companion illustration")
+ }
+ if err := registry.Close(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ s.owner = openNicknamePlayer(t, factory, accounts[0])
+ var actualIndex uint64
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ granted, err := p.ownedItems.GrantOnce(ctx, "explicit-illustration", []gamedata.BattleReward{{Type: 25, ID: 274, Count: 1}})
+ if err != nil || len(granted) != 1 {
+ t.Fatalf("grant separate illustration item: %v", err)
+ }
+ actualIndex = granted[0].InvenIndex
+ })
+ closeNicknamePlayer(t, s.owner)
+ registry = newPlayerRegistry(factory, time.Minute)
+ a = friendHTTPLogin(t, registry, accounts[0])
+ if row := find(appRows(a.send("/ItemInfo", nil, 21, 0), 1), 25, 274); row == nil || appValue(row, 1) != actualIndex {
+ t.Fatal("an existing illustration item was duplicated or replaced by the skin ownership view")
+ }
+}
diff --git a/go/internal/server/app/quest_battle_integration_test.go b/go/internal/server/app/quest_battle_integration_test.go
index 1bc733b..253e947 100644
--- a/go/internal/server/app/quest_battle_integration_test.go
+++ b/go/internal/server/app/quest_battle_integration_test.go
@@ -78,10 +78,14 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
t.Error(err)
}
})
+ session := scenario.name
run := func(identity, path string, body []byte) []byte {
t.Helper()
request := registryCommand(accounts[0], scenario.name+identity, path, body)
- request.Identity.SessionID = scenario.name
+ request.Identity.SessionID = session
+ if path == "/LoginUser" {
+ request.LoginSessionKey = []byte("0123456789abcdef0123456789abcdef")
+ }
reply := registryExecute(t, runtime, request)
return reply.Responses[0].Body
}
@@ -112,6 +116,38 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
if appValue(response, 2) != scenario.selected {
t.Fatalf("client receives wrong enemy deck: %d, want %d", appValue(response, 2), scenario.selected)
}
+ reenter := func(identity string) {
+ t.Helper()
+ if err := owner.Recover(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ session += "-reconnected"
+ run(identity+"-login", "/LoginUser", appScalar(1, 1))
+ pack := run(identity+"-pack", "/PackInGameInfo", append(appScalar(1, 2), appScalar(2, 1)...))
+ // CommonPacket consumes field 17 before GameFieldManager opens BattleResumePopupUI.
+ positions := appRows(pack, 4)
+ if appValue(pack, 17) != 1 || len(appRows(pack, 2)) == 0 || len(positions) != 1 || len(positions[0]) == 0 {
+ t.Fatal("relogin could not load the field and offer the unfinished battle")
+ }
+ other := registryCommand(accounts[0], scenario.name+identity+"-switch-pack", "/PackInGameInfo", append(appScalar(1, 3), appScalar(2, 2)...))
+ other.Identity.SessionID = session
+ future, err := runtime.Submit(context.Background(), other)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := future.Wait(context.Background()); err == nil {
+ t.Fatal("unfinished battle allowed switching to another pack")
+ }
+ if owner.assembly.wallet.Snapshot(command.Context{}).Gold != beforeGold || !maps.Equal(appItemTotals(run(identity+"-items", "/ItemInfo", appScalar(1, 4))), beforeItems) {
+ t.Fatal("relogin granted battle rewards before victory")
+ }
+ }
+ reenter("before-start")
+ initial := run("resume-before-start", "/BattleResume", appScalar(1, 5))
+ commons := appRows(initial, 1)
+ if appValue(initial, 22) != 1 || len(commons) != 1 || appValue(commons[0], 2) != scenario.selected || appValue(initial, 5) != uint64(scenario.activeQuest) {
+ t.Fatal("session expiry before BattleStart lost the pending encounter")
+ }
blue := appScalar(3, 300)
common := append(appScalar(1, 1), appScalar(2, scenario.selected)...)
checkpoint := appMessage(1, common)
@@ -120,9 +156,7 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
start := append(appScalar(1, 3), appScalar(2, scenario.selected)...)
start = append(start, appMessage(100, checkpoint)...)
run("start", "/BattleStart", start)
- if err := owner.Recover(context.Background()); err != nil {
- t.Fatal(err)
- }
+ reenter("after-start")
resume := run("resume", "/BattleResume", appScalar(1, 101))
if appValue(resume, 5) != uint64(scenario.activeQuest) {
t.Fatal("story battle recovery lost its actual owning quest")
@@ -166,6 +200,10 @@ func TestQuestBattleUsesItsOwnQuestDifficultyAndRewardOwner(t *testing.T) {
if totals := appItemTotals(run("items-retry", "/ItemInfo", appScalar(1, 6))); !maps.Equal(totals, afterItems) {
t.Fatal("settlement retry credited owned items twice")
}
+ pack := run("settled-pack", "/PackInGameInfo", append(appScalar(1, 7), appScalar(2, 1)...))
+ if appValue(pack, 17) != 0 {
+ t.Fatal("settled encounter still offered battle recovery")
+ }
})
}
}
diff --git a/go/internal/server/app/realtime_tickets.go b/go/internal/server/app/realtime_tickets.go
index 9df6f04..102a40d 100644
--- a/go/internal/server/app/realtime_tickets.go
+++ b/go/internal/server/app/realtime_tickets.go
@@ -1,11 +1,10 @@
package app
import (
+ "bd2server/internal/common/util"
"bytes"
"context"
- "crypto/rand"
"crypto/sha256"
- "encoding/base64"
"encoding/json"
"errors"
"io"
@@ -99,12 +98,11 @@ func (t *realtimeTickets) ServeHTTP(w http.ResponseWriter, r *http.Request) {
http.Error(w, "instance changed", http.StatusConflict)
return
}
- var secret [32]byte
- if _, err := rand.Read(secret[:]); err != nil {
+ token, err := util.RandomBase64URL(32)
+ if err != nil {
http.Error(w, "ticket unavailable", http.StatusServiceUnavailable)
return
}
- token := base64.RawURLEncoding.EncodeToString(secret[:])
key := sha256.Sum256([]byte(token))
now := time.Now()
expires := now.Add(30 * time.Second)
diff --git a/go/internal/server/app/resource_item_integration_test.go b/go/internal/server/app/resource_item_integration_test.go
new file mode 100644
index 0000000..7abdc10
--- /dev/null
+++ b/go/internal/server/app/resource_item_integration_test.go
@@ -0,0 +1,62 @@
+//go:build integration
+
+package app
+
+import (
+ "bytes"
+ "testing"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+)
+
+func TestRealCostumeSelectorConsumesTicketAndRestoresChosenCostume(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
+ t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
+ var selected, index uint64
+ for id := range factory.design.resourceItems.Selections[1501] {
+ if _, owned := s.owner.assembly.collection.CostumeByID(id); !owned {
+ selected = id
+ break
+ }
+ }
+ if selected == 0 {
+ t.Fatal("selector has no unowned allowed costume")
+ }
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ items, err := p.ownedItems.GrantOnce(ctx, "selector-earned-ticket", []gamedata.BattleReward{{Type: 8, ID: 1501, Count: 2}})
+ if err != nil || len(items) != 1 {
+ t.Fatalf("earn selector ticket: %v", err)
+ }
+ index = items[0].InvenIndex
+ })
+ s.reopen(t)
+ request := wire.AppendVarint(wire.AppendVarint(trapRequest(1, index), 3, 1), 4, selected)
+ response := s.protocol(t, "/UseResourceItem", request)
+ chosen, owned := s.owner.assembly.collection.CostumeByID(selected)
+ if !owned || chosen.Level != 0 {
+ t.Fatal("using an earned selector did not grant the chosen first costume")
+ }
+ s.reopen(t)
+ if !bytes.Equal(response, s.protocol(t, "/UseResourceItem", request)) {
+ t.Fatal("selector retry lost the committed response")
+ }
+ restored, owned := s.owner.assembly.collection.CostumeByID(selected)
+ if !owned || restored.Level != 0 {
+ t.Fatal("selector retry granted an extra enhancement")
+ }
+ count := appItemTotals(s.protocol(t, "/ItemInfo", appScalar(1, 4)))[[2]uint64{8, 1501}]
+ if count != 1 {
+ t.Fatal("selector retry consumed a second ticket")
+ }
+ other := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
+ defer closeNicknamePlayer(t, other.owner)
+ if _, err := other.execute("/UseResourceItem", request); err == nil {
+ t.Fatal("another account used a ticket it does not own")
+ }
+ if _, owned := other.owner.assembly.collection.CostumeByID(selected); owned {
+ t.Fatal("selector costume crossed account boundaries")
+ }
+}
diff --git a/go/internal/server/app/reward_state_integration_test.go b/go/internal/server/app/reward_state_integration_test.go
new file mode 100644
index 0000000..7738639
--- /dev/null
+++ b/go/internal/server/app/reward_state_integration_test.go
@@ -0,0 +1,370 @@
+//go:build integration
+
+package app
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "fmt"
+ "slices"
+ "testing"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+)
+
+func TestCostumeOverflowPaysCompensationWithoutRepeatingCollectionNotice(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ for _, scenario := range []struct {
+ name string
+ costume uint64
+ goldThreadPerCopy uint64
+ }{
+ {"starter", 64701, 2},
+ {"earned", 1401, 2},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
+ t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
+ grant := func(key string, count uint64) []byte {
+ t.Helper()
+ var bundle []byte
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ var err error
+ bundle, err = p.eventEconomy.Apply(ctx, scenario.name+":"+key, nil, []gamedata.Reward{{Type: 11, ID: scenario.costume, Count: count}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ })
+ return bundle
+ }
+ costume, owned := s.owner.assembly.collection.CostumeByID(scenario.costume)
+ if scenario.name == "earned" {
+ if owned {
+ t.Fatal("new costume is already owned before its first reward")
+ }
+ rows := appRows(grant("first-copy", 1), 3)
+ if len(rows) != 1 || appValue(rows[0], 2) != scenario.costume {
+ t.Fatal("first copy did not deliver the costume")
+ }
+ costume, owned = s.owner.assembly.collection.CostumeByID(scenario.costume)
+ }
+ if !owned || costume.Level > 4 {
+ t.Fatal("costume cannot exercise the actual final enhancement")
+ }
+ for level := costume.Level; level < 4; level++ {
+ grant(fmt.Sprintf("enhance-%d", level), 1)
+ }
+ upgrade := appRows(grant("final-enhancement", 1), 9)
+ if len(upgrade) != 1 || appValue(upgrade[0], 4) != 4 || appValue(upgrade[0], 5) != 5 {
+ t.Fatal("a genuine +4 to +5 enhancement lost its collection notification")
+ }
+ s.reopen(t)
+ book := s.protocol(t, "/PictorialBookInfo", appScalar(1, uint64(s.commands+1)))
+ before := s.owner.assembly.wallet.Snapshot(command.Context{}).Mileage
+ bundle := grant("two-overflow-copies", 2)
+ if len(appRows(bundle, 9)) != 0 || len(appRows(bundle, 2)) != 0 || len(appRows(bundle, 3)) != 0 {
+ t.Fatal("overflow falsely announced new ownership or an enhancement")
+ }
+ exchanges := appRows(bundle, 8)
+ if len(exchanges) != 2 {
+ t.Fatal("two overflow copies did not produce their compensation records")
+ }
+ for _, exchange := range exchanges {
+ if appValue(exchange, 1) != 11 || appValue(exchange, 2) != scenario.costume || appValue(exchange, 4) != 20 || appValue(exchange, 6) != scenario.goldThreadPerCopy {
+ t.Fatal("overflow compensation differs from CostumeGrowthTable's gold thread reward")
+ }
+ }
+ s.reopen(t)
+ if !bytes.Equal(bundle, grant("two-overflow-copies", 2)) {
+ t.Fatal("reward retry changed the committed overflow receipt")
+ }
+ s.reopen(t)
+ costume, _ = s.owner.assembly.collection.CostumeByID(scenario.costume)
+ if costume.Level != 5 || s.owner.assembly.wallet.Snapshot(command.Context{}).Mileage != before+2*scenario.goldThreadPerCopy {
+ t.Fatal("overflow retry changed enhancement or credited compensation twice")
+ }
+ if !bytes.Equal(book, s.protocol(t, "/PictorialBookInfo", appScalar(1, uint64(s.commands+1)))) {
+ t.Fatal("overflow changed the already completed collection bonus")
+ }
+ })
+ }
+}
+
+// NewsUI uses CommunityWebLinkTable's displayed rewards and NoticePacket restores
+// claim markers before enabling the same buttons after login.
+func TestCommunityRewardCreditsOnceAndRestoresPerAccountClaims(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ players := make([]*trapPlayerScenario, 2)
+ for i, account := range accounts {
+ s := &trapPlayerScenario{factory: factory, account: account, owner: openNicknamePlayer(t, factory, account)}
+ players[i] = s
+ t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
+ }
+ a, b := players[0], players[1]
+ before := a.owner.assembly.wallet.Snapshot(command.Context{}).FreeJewelry
+ request := trapRequest(1, 1)
+ result := a.protocol(t, "/CommunityReward", request)
+ rewards := appRows(appRows(result, 1)[0], 1)
+ var displayed uint64
+ for _, reward := range rewards {
+ if appValue(reward, 3) == 3 {
+ displayed += appValue(reward, 4)
+ }
+ }
+ // CommunityWebLinkTable 0 in GameData 20261012190548 advertises 100 free diamonds.
+ if displayed != 100 || a.owner.assembly.wallet.Snapshot(command.Context{}).FreeJewelry != before+100 {
+ t.Fatal("community reward shown by the client was not credited to spendable diamonds")
+ }
+ a.protocol(t, "/CommunityReward", trapRequest(2, 1))
+ a.reopen(t)
+ rows := appRows(a.protocol(t, "/CommunityRewardInfo", appScalar(1, 3)), 1)
+ if len(rows) != 1 || appValue(rows[0], 1) != 1 {
+ t.Fatal("relogin made the already-claimed community button claimable again")
+ }
+ a.protocol(t, "/CommunityReward", trapRequest(4, 1))
+ if got := a.owner.assembly.wallet.Snapshot(command.Context{}).FreeJewelry; got != before+displayed {
+ t.Fatal("community reward replay credited diamonds again")
+ }
+ if rows := appRows(b.protocol(t, "/CommunityRewardInfo", appScalar(1, 1)), 1); len(rows) != 0 {
+ t.Fatal("one player's community claims disabled another player's buttons")
+ }
+ _, err := a.execute("/CommunityReward", wire.AppendVarint(trapRequest(5, 0), 3, 999999))
+ if err == nil {
+ t.Fatal("a nonexistent survey granted its displayed reward")
+ }
+}
+
+// GameData's InteractionAchievementTable gives illustration 1065193 point 1/1
+// independent motions 0..4. Client saves only new motions, not a full snapshot.
+func TestInteractionDeltasSurviveRelogWithoutErasingEarlierDiscoveries(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
+ t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ if _, err := p.ownedItems.GrantOnce(ctx, "interaction-owned-illustration", []gamedata.BattleReward{{Type: 45, ID: 65193, Count: 1}}); err != nil {
+ t.Fatal(err)
+ }
+ })
+ save := func(motion uint64) []byte {
+ point := wire.AppendVarint(nil, 1, 1)
+ point = wire.AppendVarint(point, 2, motion)
+ group := wire.AppendVarint(nil, 1, 1065193)
+ group = wire.AppendVarint(group, 2, 1)
+ group = wire.AppendBytes(group, 3, point)
+ return wire.AppendBytes(appScalar(1, uint64(s.commands+1)), 2, group)
+ }
+ s.protocol(t, "/SpineInteractionAchievementSave", save(0))
+ s.reopen(t)
+ s.protocol(t, "/SpineInteractionAchievementSave", save(1))
+ s.protocol(t, "/SpineInteractionAchievementSave", save(0))
+ s.reopen(t)
+ assertMotions := func() {
+ t.Helper()
+ groups := appRows(s.protocol(t, "/SpineInteractionAchievementInfo", appScalar(1, uint64(s.commands+1))), 1)
+ if len(groups) != 1 || appValue(groups[0], 1) != 1065193 || appValue(groups[0], 2) != 1 {
+ t.Fatal("relogin did not restore the illustration's discovered group")
+ }
+ points := appRows(groups[0], 3)
+ var motions []uint64
+ if len(points) != 1 || appValue(points[0], 1) != 1 {
+ t.Fatal("saved discoveries appeared on another interaction point")
+ }
+ if err := wire.Walk(points[0], func(f wire.Field) error {
+ if f.Number == 2 {
+ if f.Type != 0 && f.Type != 2 {
+ return wire.ErrMalformed
+ }
+ for raw := f.Value; len(raw) > 0; {
+ value, count := binary.Uvarint(raw)
+ if count <= 0 {
+ return wire.ErrMalformed
+ }
+ motions = append(motions, value)
+ raw = raw[count:]
+ }
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if !slices.Equal(motions, []uint64{0, 1}) {
+ t.Fatalf("incremental save or retry lost/doubled prior motion discoveries: %v", motions)
+ }
+ }
+ assertMotions()
+ if _, err := s.execute("/SpineInteractionAchievementSave", save(999999)); err == nil {
+ t.Fatal("an unlisted motion was accepted as discovered")
+ }
+ if err := s.owner.Recover(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ assertMotions()
+ other := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
+ defer closeNicknamePlayer(t, other.owner)
+ if rows := appRows(other.protocol(t, "/SpineInteractionAchievementInfo", appScalar(1, 1)), 1); len(rows) != 0 {
+ t.Fatal("another player's private interaction discoveries leaked")
+ }
+}
+
+// TotalWarPacket registers owned costumes before sending their damage. Its
+// persistent best result controls the daily reward button across later logins.
+func TestTotalWarResultRestoresDailyRewardWithoutDuplicatingInventory(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
+ t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
+ var participant []byte
+ var costumeID uint64
+ for _, costume := range s.owner.assembly.collection.Costumes() {
+ definition, found := factory.design.regularGacha.Character(costume.ID)
+ if !found {
+ continue
+ }
+ for _, character := range s.owner.assembly.worldService.CharacterService().RawAll() {
+ if definition.ID != character.ID && !slices.Contains(definition.GrowthCharacterIDs, character.ID) {
+ continue
+ }
+ participant = appScalar(1, 1)
+ participant = append(participant, appScalar(2, character.InvenIndex)...)
+ participant = append(participant, appScalar(3, character.ID)...)
+ participant = append(participant, appScalar(4, character.HP)...)
+ participant = append(participant, appScalar(5, max(character.Level, 1))...)
+ participant = append(participant, appScalar(6, costume.InvenIndex)...)
+ participant = append(participant, appScalar(7, costume.ID)...)
+ costumeID = costume.ID
+ break
+ }
+ if costumeID != 0 {
+ break
+ }
+ }
+ if costumeID == 0 {
+ t.Fatal("starter roster cannot participate in total war")
+ }
+ deckEntry := appScalar(2, appValue(participant, 6))
+ deckEntry = append(deckEntry, appScalar(3, appValue(participant, 2))...)
+ s.protocol(t, "/TotalWarDeckSave", wire.AppendBytes(appScalar(1, 100), 2, deckEntry))
+ deckBody := s.protocol(t, "/TotalWarDeckInfo", appScalar(1, 101))
+ for _, contents := range appRows(deckBody, 2) {
+ if appValue(contents, 1) != appValue(participant, 2) {
+ continue
+ }
+ participant = append(participant, appScalar(29, appValue(contents, 3))...)
+ for _, ref := range appRows(contents, 2) {
+ if id := appValue(ref, 1); id != 0 {
+ participant = append(participant, appScalar(12, id)...)
+ }
+ }
+ }
+ // BattlePlayData.SetPlayDataTotalWar reads pack3005 BattleDeck 1 and sets
+ // its monster HP to one million before TotalWarPacket sends the roster.
+ enemies := []byte{}
+ for i, enemy := range factory.design.castle.TotalWarEnemies {
+ red := appScalar(1, uint64(i+100))
+ red = append(red, appScalar(3, enemy.ID)...)
+ red = append(red, appScalar(4, 1000000)...)
+ red = append(red, appScalar(5, enemy.Level)...)
+ red = append(red, appScalar(9, uint64(i))...)
+ enemies = wire.AppendBytes(enemies, 4, red)
+ }
+ start := append(wire.AppendBytes(trapRequest(1, 1), 3, participant), enemies...)
+ s.protocol(t, "/TotalWarBattleStart", start)
+ s.reopen(t)
+ // Current TotalWarRewardTable's first tier starts at 10,000 damage and
+ // grants auto-open box 905001 (gold 2000 + material 603 x1).
+ end := wire.AppendBytes(appScalar(1, 2), 2, trapRequest(costumeID, 10000))
+ s.protocol(t, "/TotalWarBattleEnd", end)
+ s.reopen(t)
+ if appValue(s.protocol(t, "/TotalWarRewardState", appScalar(1, 3)), 1) != 1 {
+ t.Fatal("a committed qualifying result lost its unclaimed daily reward on login")
+ }
+ before := appItemTotals(s.protocol(t, "/ItemInfo", appScalar(1, 4)))[[2]uint64{8, 603}]
+ goldBefore := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
+ s.protocol(t, "/TotalWarReward", appScalar(1, 5))
+ after := appItemTotals(s.protocol(t, "/ItemInfo", appScalar(1, 6)))[[2]uint64{8, 603}]
+ if after != before+1 || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != goldBefore+2000 {
+ t.Fatal("total war daily reward did not credit its authored gold and material")
+ }
+ s.reopen(t)
+ if appValue(s.protocol(t, "/TotalWarRewardState", appScalar(1, 7)), 1) != 0 {
+ t.Fatal("claimed total war daily reward became claimable again after login")
+ }
+ if _, err := s.execute("/TotalWarReward", appScalar(1, 8)); err == nil {
+ t.Fatal("a new request claimed the same day's reward twice")
+ }
+ if err := s.owner.Recover(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if appItemTotals(s.protocol(t, "/ItemInfo", appScalar(1, 9)))[[2]uint64{8, 603}] != after || s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != goldBefore+2000 {
+ t.Fatal("rejected repeated daily claim changed owned rewards")
+ }
+ s.protocol(t, "/TotalWarBattleStart", append(wire.AppendBytes(trapRequest(10, 1), 3, participant), enemies...))
+ s.protocol(t, "/TotalWarBattleEnd", wire.AppendBytes(appScalar(1, 11), 2, trapRequest(costumeID, 1)))
+ s.reopen(t)
+ result := s.protocol(t, "/TotalWarInfo", appScalar(1, 12))
+ rows := appRows(result, 1)
+ if len(rows) != 1 || appValue(rows[0], 1) != costumeID || appValue(rows[0], 2) != 10000 {
+ t.Fatal("replaying a lower score replaced the committed best result")
+ }
+ other := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
+ defer closeNicknamePlayer(t, other.owner)
+ if len(other.protocol(t, "/TotalWarInfo", appScalar(1, 1))) != 0 {
+ t.Fatal("total war scores crossed account boundaries")
+ }
+}
+
+func TestExternalLifeRewardsAndShopConsumeTheSamePersistedBalance(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ s := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
+ t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
+ var group, id, price, itemID, quantity uint64
+ for key, row := range factory.design.life.Tables["LifeBuyItemTable"] {
+ // LifeShopUI sends group/id/count; LifeBuyItemTable defines the life-coin
+ // payment and life-material quantity displayed by that shop entry.
+ if appValue(row, 8) == 64 && appValue(row, 5) == 66 && appValue(row, 6) != 0 {
+ group, id, price = key[0], key[1], appValue(row, 6)
+ itemID, quantity = appValue(row, 4), appValue(row, 3)
+ break
+ }
+ }
+ if price == 0 || quantity == 0 {
+ t.Fatal("current life shop has no coin-funded material purchase")
+ }
+ grant := func(ctx command.Context, p *playerAssembly) {
+ t.Helper()
+ if _, err := p.eventEconomy.Apply(ctx, "external-life-reward", nil, []gamedata.Reward{{Type: 64, Count: price * 2}}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ s.run(t, true, grant)
+ request := trapRequest(1, group)
+ request = wire.AppendVarint(request, 3, id)
+ request = wire.AppendVarint(request, 4, 1)
+ s.protocol(t, "/LifeShopBuy", request)
+ s.reopen(t)
+ // Replaying the external entitlement after spending must not refill coins.
+ s.run(t, true, grant)
+ profile := s.protocol(t, "/LifeUserInfo", appScalar(1, 2))
+ users := appRows(profile, 2)
+ if len(users) != 1 || appValue(users[0], 1) != price {
+ t.Fatal("external reward and life shop used different balances or replay refilled spent coins")
+ }
+ info := s.protocol(t, "/LifeInfo", appScalar(1, 3))
+ var acquired uint64
+ for _, item := range appRows(info, 3) {
+ if appValue(item, 2) == itemID && appValue(item, 3) == 66 {
+ acquired += appValue(item, 4)
+ }
+ }
+ if acquired != quantity {
+ t.Fatal("spent life coins did not restore the purchased materials after database reopen")
+ }
+ other := &trapPlayerScenario{factory: factory, account: accounts[1], owner: openNicknamePlayer(t, factory, accounts[1])}
+ defer closeNicknamePlayer(t, other.owner)
+ otherUsers := appRows(other.protocol(t, "/LifeUserInfo", appScalar(1, 1)), 2)
+ if len(otherUsers) != 1 || appValue(otherUsers[0], 1) != 0 {
+ t.Fatal("external life rewards changed another account's life-coin balance")
+ }
+}
diff --git a/go/internal/server/app/roguelike_integration_test.go b/go/internal/server/app/roguelike_integration_test.go
new file mode 100644
index 0000000..b1e9227
--- /dev/null
+++ b/go/internal/server/app/roguelike_integration_test.go
@@ -0,0 +1,226 @@
+//go:build integration
+
+package app
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bytes"
+ "encoding/binary"
+ "testing"
+)
+
+// The packet numbers, 1-based sequence, and independent run roster follow
+// Proto.Net.PacketCodeTypeProto, RogueLikePacket.CreateDeckList and BattlePacket.
+func TestRogueLikeNativeBattleReopenAndTicketConsumption(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ a := &trapPlayerScenario{factory: factory, account: accounts[0], owner: openNicknamePlayer(t, factory, accounts[0])}
+ t.Cleanup(func() { closeNicknamePlayer(t, a.owner) })
+ seq := uint64(1)
+ call := func(path string, body []byte, code int) []byte {
+ t.Helper()
+ reply, e := a.execute(path, body)
+ if e != nil {
+ t.Fatalf("%s: %v", path, e)
+ }
+ if len(reply.Responses) != 1 || reply.Responses[0].PacketCode != code {
+ t.Fatalf("%s packet mismatch: %+v", path, reply.Responses)
+ }
+ if e = wire.Walk(reply.Responses[0].Body, func(wire.Field) error { return nil }); e != nil {
+ t.Fatal(e)
+ }
+ return reply.Responses[0].Body
+ }
+ var before uint64
+ a.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ var e error
+ before, e = p.eventEconomy.CurrencyBalance(ctx, 35)
+ if e != nil {
+ t.Fatal(e)
+ }
+ rule := p.design.roguelike.Open
+ grants := []gamedata.BattleReward{{Type: 19, ID: rule.TicketID, Count: 1}}
+ pack := p.design.roguelike.PackOpen
+ if pack.TicketID != 0 {
+ grants = append(grants, gamedata.BattleReward{Type: 19, ID: pack.TicketID, Count: 1})
+ }
+ if _, e = p.ownedItems.GrantOnce(ctx, "roguelike-unlock-test", grants); e != nil {
+ t.Fatal(e)
+ }
+ })
+ a.reopen(t)
+ call("/PackInGameInfo", trapRequest(seq, factory.design.roguelike.Pack), 5)
+ seq++
+ call("/EvilCastleRogueLikeInfo", appScalar(1, seq), 279)
+ seq++
+ entered := call("/EvilCastleRogueLikeEnter", trapRequest(seq, 1), 280)
+ seq++
+ draftUnique := map[uint64]bool{}
+ for i := range 5 {
+ choice := appRows(entered, 2)
+ if len(choice) == 0 {
+ t.Fatal("draft choice absent")
+ }
+ ids := []uint64{}
+ if e := wire.Walk(choice[0], func(f wire.Field) error {
+ if f.Number == 2 && f.Type == 0 {
+ v, k := binary.Uvarint(f.Value)
+ if k <= 0 {
+ return wire.ErrMalformed
+ }
+ ids = append(ids, v)
+ }
+ return nil
+ }); e != nil {
+ t.Fatal(e)
+ }
+ if len(ids) == 0 {
+ t.Fatal("draft offered no costumes")
+ }
+ b := trapRequest(seq, 1)
+ seq++
+ selected := ids[0]
+ if i == 0 {
+ counts := map[uint64]int{}
+ for _, c := range factory.design.roguelike.Costumes {
+ counts[c.Unique]++
+ }
+ for _, id := range ids {
+ if counts[factory.design.roguelike.Costumes[id].Unique] == 1 {
+ selected = id
+ break
+ }
+ }
+ }
+ for _, id := range ids {
+ if i == 0 {
+ break
+ }
+ unique := factory.design.roguelike.Costumes[id].Unique
+ if !draftUnique[unique] {
+ selected = id
+ draftUnique[unique] = true
+ break
+ }
+ }
+ b = wire.AppendVarint(b, 4, selected)
+ entered = call("/EvilCastleRogueLikeSelectReward", b, 283)
+ a.reopen(t)
+ }
+ info := call("/EvilCastleRogueLikeInfo", appScalar(1, seq), 279)
+ seq++
+ characters, costumes := appRows(info, 5), appRows(info, 6)
+ if len(costumes) != 5 || len(characters) == 0 {
+ t.Fatal("draft roster was not persisted")
+ }
+ char := characters[0]
+ index := appValue(char, 1)
+ var costume []byte
+ for _, c := range costumes {
+ if appValue(c, 1) == appValue(char, 7) {
+ costume = c
+ }
+ }
+ if costume == nil {
+ t.Fatal("draft character lost costume ownership")
+ }
+ deck := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, index), 2, 0), 3, 1)
+ save := wire.AppendBytes(appScalar(1, seq), 2, deck)
+ seq++
+ call("/EvilCastleRogueLikeDeckSave", save, 285)
+ floors := appRows(info, 3)
+ room := appRows(floors[0], 2)[0]
+ group, id := appValue(room, 2), appValue(room, 3)
+ definition := factory.design.roguelike.Rooms.Row(group, id)
+ battleDeck := definition.V(1)
+ call("/EvilCastleRogueLikeRoomEnter", trapRequest(seq, appValue(room, 1)), 282)
+ seq++
+ enter := wire.AppendVarint(wire.AppendVarint(appScalar(1, seq), 4, battleDeck), 5, 21)
+ seq++
+ call("/BattleEnter", enter, 52)
+ start := wire.AppendBytes(trapRequest(seq, battleDeck), 3, deck)
+ seq++
+ blue := wire.AppendVarint(nil, 1, 1)
+ for _, f := range []struct {
+ to int
+ value uint64
+ }{{2, index}, {3, appValue(char, 2)}, {4, appValue(char, 3)}, {5, appValue(char, 4)}, {6, appValue(costume, 1)}, {7, appValue(costume, 2)}, {8, appValue(costume, 3)}} {
+ blue = wire.AppendVarint(blue, f.to, f.value)
+ }
+ start = wire.AppendBytes(start, 5, blue)
+ for i, enemy := range factory.design.roguelike.Enemies[battleDeck] {
+ red := wire.AppendVarint(nil, 1, uint64(i+2))
+ red = wire.AppendVarint(red, 3, enemy.ID)
+ red = wire.AppendVarint(red, 4, 1)
+ red = wire.AppendVarint(red, 5, enemy.Level)
+ red = wire.AppendVarint(red, 9, enemy.Position)
+ start = wire.AppendBytes(start, 4, red)
+ }
+ forged, _, e := wire.ReplaceVarint(blue, 7, appValue(costume, 2)+1)
+ if e != nil {
+ t.Fatal(e)
+ }
+ var bad []byte
+ if e = wire.Walk(start, func(f wire.Field) error {
+ switch f.Number {
+ case 1:
+ bad = wire.AppendVarint(bad, 1, seq)
+ case 5:
+ bad = wire.AppendBytes(bad, 5, forged)
+ default:
+ bad = append(bad, start[f.Start:f.End]...)
+ }
+ return nil
+ }); e != nil {
+ t.Fatal(e)
+ }
+ seq++
+ a.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ if _, _, _, e := p.battleService.Handle(ctx, "/BattleStart", bad); e == nil {
+ t.Fatal("unowned battle costume bypassed the event start hook")
+ }
+ })
+ call("/BattleStart", start, 14)
+ incoming := characters[1]
+ change := wire.AppendVarint(trapRequest(seq, appValue(incoming, 1)), 3, index)
+ seq++
+ call("/EvilCastleRogueLikeBattleCharChange", change, 317)
+
+ a.reopen(t)
+ end := wire.AppendBytes(trapRequest(seq, 1), 3, char)
+ end = wire.AppendBytes(end, 3, incoming)
+ seq++
+ result := call("/BattleEnd", end, 15)
+ state := appRows(result, 17)
+ if len(state) != 1 || appValue(state[0], 3) != 1 {
+ t.Fatal("normal battle settlement did not produce a run reward choice")
+ }
+ if !bytes.Equal(result, call("/BattleEnd", end, 15)) {
+ t.Fatal("normal battle replay changed settlement")
+ }
+ a.reopen(t)
+ resumed := call("/EvilCastleRogueLikeInfo", appScalar(1, seq), 279)
+ seq++
+ if appValue(appRows(resumed, 1)[0], 3) != 1 || len(appRows(resumed, 8)) != 1 {
+ t.Fatal("reopening lost pending battle rewards")
+ }
+ a.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ after, e := p.eventEconomy.CurrencyBalance(ctx, 35)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if before == 0 || after >= before {
+ t.Fatal("entry did not consume real account tickets")
+ }
+ })
+ choice := appRows(resumed, 8)[0]
+ selected := wire.AppendVarint(trapRequest(seq, 1), 4, appValue(choice, 2))
+ seq++
+ call("/EvilCastleRogueLikeSelectReward", selected, 283)
+ a.reopen(t)
+ resumed = call("/EvilCastleRogueLikeInfo", appScalar(1, seq), 279)
+ if appValue(appRows(resumed, 1)[0], 1) <= 1 {
+ t.Fatalf("reward claim did not advance the resumed run: %x", resumed)
+ }
+}
diff --git a/go/internal/server/app/serve.go b/go/internal/server/app/serve.go
index 1bc8760..71a75e1 100644
--- a/go/internal/server/app/serve.go
+++ b/go/internal/server/app/serve.go
@@ -3,6 +3,7 @@ package app
import (
commonconfig "bd2server/internal/common/config"
"bd2server/internal/common/i18n"
+ "bd2server/internal/common/util"
"bd2server/internal/common/versionconfig"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/events/calendar"
@@ -15,8 +16,6 @@ import (
"bd2server/internal/server/platform/updates"
identitystore "bd2server/internal/server/storage/identity"
"context"
- "crypto/rand"
- "encoding/hex"
"errors"
"fmt"
"log/slog"
@@ -107,11 +106,10 @@ func Serve(args []string) (serveErr error) {
authHandler = authService.Handler()
}
availability := lifecycle.NewGate()
- instanceBytes := make([]byte, 16)
- if _, err := rand.Read(instanceBytes); err != nil {
+ instanceID, err := util.RandomHex(16)
+ if err != nil {
return fmt.Errorf("create server instance identity: %w", err)
}
- instanceID := hex.EncodeToString(instanceBytes)
realtime, err := openRealtime(c, registry, game, shared, instanceID)
if err != nil {
return err
@@ -170,6 +168,7 @@ func Serve(args []string) (serveErr error) {
AuthenticationHandler: authHandler, ResourcePolicy: c.publicResources,
CommerceManifest: func() any { return design.cashCatalog.Manifest() }, Availability: availability, InstanceID: instanceID, RealtimeTickets: realtimeTickets,
StoryCheckpoints: storyCheckpoints{game: game, players: registry}, Console: console.Handler(),
+ SpineRecordings: spineRecordings{players: registry},
LoginsClosed: func() bool { return loginsClosed(0) != "" },
Releases: releaseFiles(filepath.Join(c.dataDir, "releases")),
ClientAllowed: compatibility.allowed,
diff --git a/go/internal/server/app/shared_popularity.go b/go/internal/server/app/shared_popularity.go
new file mode 100644
index 0000000..ec1add8
--- /dev/null
+++ b/go/internal/server/app/shared_popularity.go
@@ -0,0 +1,484 @@
+package app
+
+import (
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/domain/roster/deck"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/outbox"
+ "bd2server/internal/server/storage/shared"
+ "context"
+ "encoding/json"
+ "fmt"
+ "math"
+ "slices"
+ "strconv"
+ "strings"
+ "time"
+)
+
+const popularityWeekMS uint64 = 7 * 24 * 60 * 60 * 1000
+
+// Friday 00:00 KST is Thursday 15:00 UTC.
+func popularityWeek(at uint64) uint64 {
+ const anchor uint64 = 15 * 60 * 60 * 1000
+ if at < anchor {
+ return 0
+ }
+ return (at - anchor) / popularityWeekMS
+}
+func popularityContext(content, side, order, rank, stage uint64) string {
+ return fmt.Sprintf("%d:%d:%02d:%010d:%010d:", content, side, order, rank, stage)
+}
+func popularityCount(tx *shared.Tx, bucket, key string, delta int64) error {
+ raw, found, e := tx.Get(bucket, key)
+ if e != nil {
+ return e
+ }
+ var n int64
+ if found && json.Unmarshal(raw, &n) != nil {
+ return fmt.Errorf("invalid popularity counter")
+ }
+ if delta < 0 && n < -delta || delta > 0 && n > math.MaxInt64-delta {
+ return fmt.Errorf("popularity counter overflow")
+ }
+ n += delta
+ if n == 0 {
+ _, e = tx.Delete(bucket, key)
+ return e
+ }
+ raw, e = json.Marshal(n)
+ if e != nil {
+ return e
+ }
+ return tx.Put(bucket, key, raw)
+}
+func popularityReplace(tx *shared.Tx, identity string, next map[string]int64) error {
+ raw, found, e := tx.Get("popularity_sources", identity)
+ if e != nil {
+ return e
+ }
+ old := map[string]int64{}
+ if found && json.Unmarshal(raw, &old) != nil {
+ return fmt.Errorf("invalid popularity source")
+ }
+ for key, n := range old {
+ if e = popularityCount(tx, "popularity_counts", key, -n); e != nil {
+ return e
+ }
+ }
+ for key, n := range next {
+ if n <= 0 {
+ return fmt.Errorf("invalid popularity contribution")
+ }
+ if e = popularityCount(tx, "popularity_counts", key, n); e != nil {
+ return e
+ }
+ }
+ raw, e = json.Marshal(next)
+ if e != nil {
+ return e
+ }
+ return tx.Put("popularity_sources", identity, raw)
+}
+func scanPopularity(tx *shared.Tx, bucket, prefix string, visit func(shared.Entry) error) error {
+ for after := ""; ; {
+ rows, e := tx.Scan(bucket, prefix, after, 256)
+ if e != nil {
+ return e
+ }
+ if len(rows) == 0 {
+ return nil
+ }
+ for _, row := range rows {
+ after = row.Key
+ if e = visit(row); e != nil {
+ return e
+ }
+ }
+ }
+}
+func rotatePopularity(tx *shared.Tx, at uint64) error {
+ week := popularityWeek(at)
+ raw, found, e := tx.Get("popularity_clock", "week")
+ if e != nil {
+ return e
+ }
+ previous := week
+ if found && json.Unmarshal(raw, &previous) != nil {
+ return fmt.Errorf("invalid popularity week")
+ }
+ if previous > week {
+ return nil
+ }
+ if previous < week {
+ for _, live := range []string{"pvp:", "total:"} {
+ if e = scanPopularity(tx, "popularity_counts", live, func(row shared.Entry) error {
+ if e := tx.Put("popularity_counts", fmt.Sprintf("week:%020d:", previous)+strings.TrimPrefix(row.Key, live), row.Value); e != nil {
+ return e
+ }
+ return nil
+ }); e != nil {
+ return e
+ }
+ }
+ }
+ raw, e = json.Marshal(week)
+ if e != nil {
+ return e
+ }
+ return tx.Put("popularity_clock", "week", raw)
+}
+
+func (s *sharedRuntime) refreshPopularity(ctx context.Context, now time.Time) error {
+ return s.store.Update(ctx, func(tx *shared.Tx) error { return rotatePopularity(tx, uint64(now.UnixMilli())) })
+}
+
+func (s *sharedRuntime) equipmentPopularity(tx *shared.Tx, source string, r *deck.RecommendRecord) error {
+ next := map[string]int64{}
+ if r != nil {
+ chars := map[uint64]uint64{}
+ for _, c := range r.Characters {
+ if v, ok := s.statistics.Characters[c.ID]; ok {
+ chars[c.InvenIndex] = v.UniqueID
+ }
+ }
+ seen := map[string]bool{}
+ for _, v := range r.Equipment {
+ unique := chars[v.UseChar]
+ design, ok := s.statistics.Equipment[v.ID]
+ if !ok || unique == 0 || design.UniqueID == 0 {
+ continue
+ }
+ key := fmt.Sprintf("equip:%010d:%d:%010d", unique, design.Slot, design.UniqueID)
+ if !seen[key] {
+ next[key]++
+ seen[key] = true
+ }
+ }
+ }
+ return popularityReplace(tx, "equipment:"+source, next)
+}
+
+func decodePopularityEquipment(raw []byte, r *deck.RecommendRecord) error {
+ return wire.Walk(raw, func(f wire.Field) error {
+ switch f.Number {
+ case 2:
+ var c roster.Character
+ var e error
+ c.InvenIndex, _, e = wire.Varint(f.Value, 1)
+ if e != nil {
+ return e
+ }
+ c.ID, _, e = wire.Varint(f.Value, 2)
+ r.Characters = append(r.Characters, c)
+ return e
+ case 4:
+ var v assets.Equipment
+ var e error
+ v.UseChar, _, e = wire.Varint(f.Value, 2)
+ if e != nil {
+ return e
+ }
+ base, _, e := wire.Bytes(f.Value, 5)
+ if e != nil {
+ return e
+ }
+ v.ID, _, e = wire.Varint(base, 1)
+ r.Equipment = append(r.Equipment, v)
+ return e
+ }
+ return nil
+ })
+}
+
+func (s *sharedRuntime) totalWarPopularity(tx *shared.Tx, source string, p deck.PopularityPublication) error {
+ if p.OwnerIndex == 0 || p.Score > math.MaxInt64 || len(p.TotalWarCostumes) > 100 {
+ return fmt.Errorf("invalid total-war popularity")
+ }
+ for _, id := range p.TotalWarCostumes {
+ if _, ok := s.statistics.CostumeGrade[id]; !ok {
+ return fmt.Errorf("unknown total-war popularity costume")
+ }
+ }
+ ownerKey := fmt.Sprintf("%020d", p.OwnerIndex)
+ owner := recommendationSource(source)
+ raw, found, e := tx.Get("popularity_total_owners", ownerKey)
+ if e != nil {
+ return e
+ }
+ if found && string(raw) != owner {
+ return fmt.Errorf("total-war popularity owner conflict")
+ }
+ if e = tx.Put("popularity_total_owners", ownerKey, []byte(owner)); e != nil {
+ return e
+ }
+ raw, found, e = tx.Get("popularity_total", owner)
+ if e != nil {
+ return e
+ }
+ if found {
+ var old deck.PopularityPublication
+ if json.Unmarshal(raw, &old) != nil {
+ return fmt.Errorf("invalid total-war popularity score")
+ }
+ if old.Score >= p.Score {
+ return nil
+ }
+ }
+ raw, e = json.Marshal(p)
+ if e != nil {
+ return e
+ }
+ if e = tx.Put("popularity_total", owner, raw); e != nil {
+ return e
+ }
+ var records []deck.PopularityPublication
+ if e = scanPopularity(tx, "popularity_total", "", func(row shared.Entry) error {
+ var p deck.PopularityPublication
+ if json.Unmarshal(row.Value, &p) != nil {
+ return fmt.Errorf("invalid total-war popularity snapshot")
+ }
+ records = append(records, p)
+ return nil
+ }); e != nil {
+ return e
+ }
+ slices.SortFunc(records, func(a, b deck.PopularityPublication) int {
+ if a.Score > b.Score {
+ return -1
+ }
+ if a.Score < b.Score {
+ return 1
+ }
+ return 0
+ })
+ next := map[string]int64{}
+ rank := 0
+ for i, r := range records {
+ if i == 0 || records[i-1].Score != r.Score {
+ rank = i + 1
+ }
+ if uint64(rank)*100 > uint64(len(records))*10 {
+ continue
+ }
+ for _, id := range r.TotalWarCostumes {
+ next["total:"+popularityContext(3, 0, 0, 0, 0)+fmt.Sprintf("%010d", id)]++
+ }
+ }
+ return popularityReplace(tx, "total-war-ranking", next)
+}
+func (s *sharedRuntime) consumePopularity(ctx context.Context, event outbox.Pending) error {
+ var p deck.PopularityPublication
+ if json.Unmarshal(event.Envelope.Event.Payload, &p) != nil || p.CompletedAt == 0 {
+ return fmt.Errorf("invalid popularity battle")
+ }
+ if len(p.TotalWarCostumes) == 0 {
+ if e := p.Record.Validate(); e != nil {
+ return e
+ }
+ }
+ if s.statistics == nil {
+ return fmt.Errorf("missing popularity design")
+ }
+ return s.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
+ if e := rotatePopularity(tx, p.CompletedAt); e != nil {
+ return e
+ }
+ if len(p.TotalWarCostumes) != 0 {
+ return s.totalWarPopularity(tx, envelope.Source, p)
+ }
+ mode := p.Record.Context.BattleMode
+ content := uint64(0)
+ switch mode {
+ case 7:
+ content = 1
+ case 16:
+ content = 2
+ case 19:
+ content = 4
+ case 20:
+ content = 5
+ default:
+ return nil
+ }
+ stage := s.statistics.CastleStages[mode][p.Record.Context.BattleIndex]
+ if stage == 0 {
+ return fmt.Errorf("unknown castle popularity stage")
+ }
+ day := p.CompletedAt / (24 * 60 * 60 * 1000)
+ receipt := fmt.Sprintf("%s:%d:%d:%d", recommendationSource(envelope.Source), mode, p.Record.Context.BattleIndex, day)
+ if _, found, e := tx.Get("popularity_castle_days", receipt); e != nil || found {
+ return e
+ }
+ active := map[uint64]bool{}
+ for _, c := range p.Record.Characters {
+ active[c.UseCostume] = true
+ }
+ for _, c := range p.Record.Costumes {
+ if !active[c.InvenIndex] {
+ continue
+ }
+ for _, filter := range []uint64{0, stage} {
+ key := fmt.Sprintf("week:%020d:", popularityWeek(p.CompletedAt)) + popularityContext(content, 0, 0, 0, filter) + fmt.Sprintf("%010d", c.ID)
+ if e := popularityCount(tx, "popularity_counts", key, 1); e != nil {
+ return e
+ }
+ if stage == 0 {
+ break
+ }
+ }
+ }
+ return tx.Put("popularity_castle_days", receipt, []byte("1"))
+ })
+}
+
+func popularityRequest(raw []byte, max int) (map[int]uint64, error) {
+ values := map[int]uint64{}
+ e := wire.Walk(raw, func(f wire.Field) error {
+ if f.Number < 1 || f.Number > max {
+ return nil
+ }
+ if f.Type != 0 {
+ return fmt.Errorf("invalid popularity request field")
+ }
+ if _, found := values[f.Number]; found {
+ return fmt.Errorf("duplicate popularity request field")
+ }
+ v, _, e := wire.Varint(raw, f.Number)
+ if e != nil || v > math.MaxInt32 {
+ return fmt.Errorf("invalid popularity request value")
+ }
+ values[f.Number] = v
+ return nil
+ })
+ if e != nil {
+ return nil, e
+ }
+ if values[1] == 0 {
+ return nil, fmt.Errorf("missing popularity sequence")
+ }
+ return values, nil
+}
+func (s *sharedRuntime) popularInfo(ctx command.Context, path string, raw []byte, now time.Time) (int, []byte, error) {
+ code := 269
+ max := 6
+ if path == "/PopularEquipInfo" {
+ code = 0
+ max = 2
+ }
+ v, e := popularityRequest(raw, max)
+ if e != nil {
+ return code, nil, e
+ }
+ if s.statistics == nil {
+ return code, nil, fmt.Errorf("missing popularity design")
+ }
+ if path == "/PopularCostumeInfo" && (v[2] > 5 || v[3] > 1 || v[4] > 4) {
+ return code, nil, fmt.Errorf("invalid popularity filter")
+ }
+ if path == "/PopularEquipInfo" {
+ known := false
+ for _, c := range s.statistics.Characters {
+ known = known || c.UniqueID == v[2]
+ }
+ if !known {
+ return code, nil, fmt.Errorf("unknown popularity character")
+ }
+ }
+ cancel := ctx.Cancellation
+ if cancel == nil {
+ cancel = context.Background()
+ }
+ var body []byte
+ e = s.store.View(cancel, func(tx *shared.Tx) error {
+ if path == "/PopularEquipInfo" {
+ prefix := fmt.Sprintf("equip:%010d:", v[2])
+ type winner struct{ id, count uint64 }
+ winners := map[uint64]winner{}
+ if e := scanPopularity(tx, "popularity_counts", prefix, func(row shared.Entry) error {
+ var count uint64
+ if json.Unmarshal(row.Value, &count) != nil {
+ return fmt.Errorf("invalid equipment popularity")
+ }
+ parts := strings.Split(strings.TrimPrefix(row.Key, prefix), ":")
+ if len(parts) != 2 {
+ return fmt.Errorf("invalid equipment popularity key")
+ }
+ slot, e := strconv.ParseUint(parts[0], 10, 64)
+ if e != nil {
+ return e
+ }
+ id, e := strconv.ParseUint(parts[1], 10, 64)
+ if e != nil {
+ return e
+ }
+ prior := winners[slot]
+ if count > prior.count || count == prior.count && (prior.id == 0 || id < prior.id) {
+ winners[slot] = winner{id, count}
+ }
+ return nil
+ }); e != nil {
+ return e
+ }
+ for slot := range uint64(5) {
+ winner, found := winners[slot]
+ if !found {
+ continue
+ }
+ b := wire.AppendVarint(nil, 1, v[2])
+ b = wire.AppendVarint(b, 2, slot)
+ b = wire.AppendVarint(b, 3, winner.id)
+ b = wire.AppendVarint(b, 4, winner.count)
+ body = wire.AppendBytes(body, 1, b)
+ }
+ return nil
+ }
+ counts := map[uint64][3]uint64{}
+ week := popularityWeek(uint64(now.UnixMilli()))
+ for i := uint64(0); i < 3 && i <= week; i++ {
+ period := week - i
+ if v[2] == 0 || v[2] == 3 {
+ if period == 0 {
+ continue
+ }
+ period--
+ }
+ prefix := fmt.Sprintf("week:%020d:", period)
+ prefix += popularityContext(v[2], v[3], v[4], v[5], v[6])
+ if e := scanPopularity(tx, "popularity_counts", prefix, func(row shared.Entry) error {
+ id, e := strconv.ParseUint(strings.TrimPrefix(row.Key, prefix), 10, 64)
+ if e != nil {
+ return e
+ }
+ var n uint64
+ if json.Unmarshal(row.Value, &n) != nil {
+ return fmt.Errorf("invalid costume popularity")
+ }
+ a := counts[id]
+ a[i] = n
+ counts[id] = a
+ return nil
+ }); e != nil {
+ return e
+ }
+ }
+ ids := make([]uint64, 0, len(counts))
+ for id := range counts {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ for _, id := range ids {
+ b := wire.AppendVarint(nil, 1, id)
+ for i, n := range counts[id] {
+ if n != 0 {
+ b = wire.AppendVarint(b, i+2, n)
+ }
+ }
+ body = wire.AppendBytes(body, 1, b)
+ }
+ return nil
+ })
+ return code, body, e
+}
diff --git a/go/internal/server/app/shared_popularity_test.go b/go/internal/server/app/shared_popularity_test.go
new file mode 100644
index 0000000..2acaa14
--- /dev/null
+++ b/go/internal/server/app/shared_popularity_test.go
@@ -0,0 +1,338 @@
+package app
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "testing"
+ "time"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/battle/pvp"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/domain/roster/deck"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/outbox"
+ "bd2server/internal/server/storage/shared"
+)
+
+func popularityFixture(t *testing.T) (*sharedRuntime, string) {
+ t.Helper()
+ directory := t.TempDir()
+ store, e := shared.Open(directory)
+ if e != nil {
+ t.Fatal(e)
+ }
+ s := &sharedRuntime{store: store, statistics: &gamedata.CollectionStatisticsDesign{Characters: map[uint64]gamedata.StatisticsCharacter{501: {UniqueID: 5, Grade: 5}}, CostumeGrade: map[uint64]uint64{101: 5, 102: 5}, Equipment: map[uint64]gamedata.StatisticsEquipment{301: {UniqueID: 900, Slot: 0}, 302: {UniqueID: 901, Slot: 0}}, CastleStages: map[uint64]map[uint64]uint64{16: {900: 1, 901: 2}}}}
+ t.Cleanup(func() {
+ if e := s.store.Close(); e != nil {
+ t.Error(e)
+ }
+ })
+ return s, directory
+}
+func popularityEvent(t *testing.T, s *sharedRuntime, source, id, topic string, value any) outbox.Pending {
+ t.Helper()
+ raw, e := json.Marshal(value)
+ if e != nil {
+ t.Fatal(e)
+ }
+ var result outbox.Pending
+ e = s.store.Update(context.Background(), func(tx *shared.Tx) error {
+ q, e := tx.Outbox()
+ if e != nil {
+ return e
+ }
+ if e = outbox.Publish(q, source, command.Event{ID: id, Topic: topic, Payload: raw}); e != nil {
+ return e
+ }
+ rows, e := outbox.Read(q, 256)
+ if e != nil {
+ return e
+ }
+ for _, r := range rows {
+ if r.Envelope.Source == source && r.Envelope.Event.ID == id {
+ result = r
+ return nil
+ }
+ }
+ return fmt.Errorf("missing committed publication")
+ })
+ if e != nil {
+ t.Fatal(e)
+ }
+ return result
+}
+func popularityRecord(owner uint64, costume, equip uint64) deck.RecommendRecord {
+ r := deck.RecommendRecord{Context: deck.RecommendContext{BattleMode: 16, BattleIndex: 900}, Identity: deck.RecommendIdentity{OwnerIndex: owner, UserID: fmt.Sprint(owner)}, Deck: []deck.DeckEntry{{CharacterInvenIndex: 11, Slot: 1}}, Characters: []roster.Character{{InvenIndex: 11, ID: 501, Level: 1, UseCostume: 21}}, Costumes: []deck.RecommendCostume{{Costume: roster.Costume{InvenIndex: 21, ID: costume, UseChar: 11}}}}
+ if equip != 0 {
+ r.Equipment = []assets.Equipment{{InvenIndex: 31, ID: equip, UseChar: 11}}
+ }
+ return r
+}
+func popularityRows(t *testing.T, s *sharedRuntime, path string, now time.Time, values ...uint64) [][]byte {
+ t.Helper()
+ raw := wire.AppendVarint(nil, 1, 1)
+ for i, v := range values {
+ raw = wire.AppendVarint(raw, i+2, v)
+ }
+ _, body, e := s.popularInfo(command.Context{}, path, raw, now)
+ if e != nil {
+ t.Fatal(e)
+ }
+ var rows [][]byte
+ if e = wire.Walk(body, func(f wire.Field) error {
+ if f.Number == 1 {
+ rows = append(rows, f.Value)
+ }
+ return nil
+ }); e != nil {
+ t.Fatal(e)
+ }
+ return rows
+}
+func popularityScalar(t *testing.T, b []byte, field int) uint64 {
+ t.Helper()
+ v, _, e := wire.Varint(b, field)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return v
+}
+
+func TestCastlePopularityCountsFirstActualBattlePerDayAndRecovers(t *testing.T) {
+ s, dir := popularityFixture(t)
+ now := time.Date(2026, 10, 17, 10, 0, 0, 0, time.UTC)
+ p := deck.PopularityPublication{CompletedAt: uint64(now.UnixMilli()), Record: popularityRecord(1, 101, 0)}
+ event := popularityEvent(t, s, "alice", "attempt-1", deck.PopularityTopic, p)
+ if e := s.consumePopularity(t.Context(), event); e != nil {
+ t.Fatal(e)
+ }
+ if e := s.consumePopularity(t.Context(), event); e != nil {
+ t.Fatal(e)
+ }
+ p.CompletedAt++
+ if e := s.consumePopularity(t.Context(), popularityEvent(t, s, "alice", "attempt-2", deck.PopularityTopic, p)); e != nil {
+ t.Fatal(e)
+ }
+ p.Record = popularityRecord(2, 102, 0)
+ if e := s.consumePopularity(t.Context(), popularityEvent(t, s, "bob", "attempt-1", deck.PopularityTopic, p)); e != nil {
+ t.Fatal(e)
+ }
+ if e := s.store.Close(); e != nil {
+ t.Fatal(e)
+ }
+ var e error
+ s.store, e = shared.Open(dir)
+ if e != nil {
+ t.Fatal(e)
+ }
+ rows := popularityRows(t, s, "/PopularCostumeInfo", now, 2, 0, 0, 0, 1)
+ if len(rows) != 2 {
+ t.Fatalf("two players' actual active costumes: %d", len(rows))
+ }
+ for _, row := range rows {
+ if got := popularityScalar(t, row, 2); got != 1 {
+ t.Fatalf("repeat battle inflated daily usage to %d", got)
+ }
+ }
+ if rows := popularityRows(t, s, "/PopularCostumeInfo", now, 4, 0, 0, 0, 1); len(rows) != 0 {
+ t.Fatal("greed usage escaped into rage content")
+ }
+ p.Record = popularityRecord(1, 101, 0)
+ p.CompletedAt = uint64(now.Add(24 * time.Hour).UnixMilli())
+ if e := s.consumePopularity(t.Context(), popularityEvent(t, s, "alice", "next-day", deck.PopularityTopic, p)); e != nil {
+ t.Fatal(e)
+ }
+ rows = popularityRows(t, s, "/PopularCostumeInfo", now.Add(24*time.Hour), 2, 0, 0, 0, 1)
+ if got := popularityScalar(t, rows[0], 2); got != 2 {
+ t.Fatalf("next reset day did not count: %d", got)
+ }
+}
+
+func TestEquipmentPopularityReplacesOwnerSnapshotAndChoosesMostUsedSlot(t *testing.T) {
+ s, _ := popularityFixture(t)
+ now := time.Date(2026, 10, 17, 10, 0, 0, 0, time.UTC)
+ for i, source := range []string{"alice", "bob", "carol"} {
+ r := popularityRecord(uint64(i+1), 101, 301)
+ r.Revision = 1
+ event := popularityEvent(t, s, source, "saved", deck.RecommendationTopic, deck.RecommendationPublication{Revision: 1, Public: true, Record: &r})
+ if e := s.consumeRecommendation(t.Context(), event); e != nil {
+ t.Fatal(e)
+ }
+ if e := s.consumeRecommendation(t.Context(), event); e != nil {
+ t.Fatal(e)
+ }
+ }
+ r := popularityRecord(1, 101, 302)
+ r.Revision = 2
+ if e := s.consumeRecommendation(t.Context(), popularityEvent(t, s, "alice", "changed", deck.RecommendationTopic, deck.RecommendationPublication{Revision: 2, Public: true, Record: &r})); e != nil {
+ t.Fatal(e)
+ }
+ rows := popularityRows(t, s, "/PopularEquipInfo", now, 5)
+ if len(rows) != 1 || popularityScalar(t, rows[0], 3) != 900 || popularityScalar(t, rows[0], 4) != 2 {
+ t.Fatalf("expected most-used item with two remaining owners: %x", rows)
+ }
+ if e := s.consumeRecommendation(t.Context(), popularityEvent(t, s, "bob", "hidden", deck.RecommendationTopic, deck.RecommendationPublication{Revision: 2, Public: false})); e != nil {
+ t.Fatal(e)
+ }
+ rows = popularityRows(t, s, "/PopularEquipInfo", now, 5)
+ if len(rows) != 1 || popularityScalar(t, rows[0], 4) != 1 {
+ t.Fatalf("withdrawn owner still counted: %x", rows)
+ }
+}
+
+func TestPopularityDoesNotFillUnobservedHistoricalWeeks(t *testing.T) {
+ first := time.Date(2026, 10, 15, 14, 59, 0, 0, time.UTC)
+ s, makeSnapshot := pvpPopularityFixture(t, first)
+ update := pvp.PopularityPublished{Timestamp: uint64(first.UnixMilli()), Snapshot: makeSnapshot(1, false)}
+ if err := s.consumePVP(t.Context(), popularityEvent(t, s, "alice", "actual-registration", "pvp.popularity", update)); err != nil {
+ t.Fatal(err)
+ }
+ published := first.Add(time.Minute)
+ if err := s.refreshPopularity(t.Context(), published); err != nil {
+ t.Fatal(err)
+ }
+ rows := popularityRows(t, s, "/PopularCostumeInfo", published, 0, 0, 0, 1, 0)
+ if len(rows) != 1 || popularityScalar(t, rows[0], 1) != 101 || popularityScalar(t, rows[0], 2) != 1 {
+ t.Fatal("the actually observed registration did not publish at the weekly boundary")
+ }
+ later := first.Add(5 * 7 * 24 * time.Hour)
+ if err := s.refreshPopularity(t.Context(), later); err != nil {
+ t.Fatal(err)
+ }
+ if rows := popularityRows(t, s, "/PopularCostumeInfo", later, 0, 0, 0, 1, 0); len(rows) != 0 {
+ t.Fatalf("unobserved weeks were synthesized: %x", rows)
+ }
+}
+
+func pvpPopularityFixture(t *testing.T, now time.Time) (*sharedRuntime, func(uint64, bool) pvp.PublishedSnapshot) {
+ t.Helper()
+ s, _ := popularityFixture(t)
+ design := &gamedata.PvpDesign{Mirror: gamedata.PvpDefaults{StartVP: 1000, MinimumVP: 1000}, MirrorSeasons: map[uint64]uint64{1: 1}, MirrorRanks: map[uint64][]gamedata.PvpRank{1: {{Group: 1, ID: 7, VP: 1000}}}}
+ var e error
+ s.pvp, e = newSharedPVP(t.Context(), s.store, design, []pvp.Season{{Mode: pvp.Mirror, ID: 1, Start: 1, End: uint64(now.AddDate(1, 0, 0).UnixMilli())}})
+ if e != nil {
+ t.Fatal(e)
+ }
+ s.statistics.PVPRankGroups = map[uint64]uint64{7: 1}
+ s.statistics.PVPMinimumGroup = 1
+ makeSnapshot := func(version uint64, reverse bool) pvp.PublishedSnapshot {
+ order := []uint64{21, 22}
+ if reverse {
+ order = []uint64{22, 21}
+ }
+ entry := wire.AppendVarint(nil, 1, 11)
+ for _, index := range order {
+ entry = wire.AppendBytes(entry, 5, wire.AppendVarint(nil, 1, index))
+ }
+ full := wire.AppendBytes(nil, 1, entry)
+ for i, id := range []uint64{101, 102} {
+ c := wire.AppendVarint(nil, 1, uint64(i+21))
+ c = wire.AppendVarint(c, 2, id)
+ full = wire.AppendBytes(full, 3, c)
+ }
+ return pvp.PublishedSnapshot{Profile: pvp.Profile{OwnerID: "alice", OwnerIndex: 1}, Mode: pvp.Mirror, Season: 1, Version: version, VP: 1000, Snapshot: pvp.FullSnapshot{FullDeck: full}}
+ }
+ return s, makeSnapshot
+}
+
+func TestPVPPopularitySeparatesRegisteredSkillOrderAndDeckSide(t *testing.T) {
+ now := time.Date(2026, 10, 15, 14, 59, 0, 0, time.UTC)
+ s, makeSnapshot := pvpPopularityFixture(t, now)
+ for side := range uint64(2) {
+ update := pvp.PopularityPublished{Timestamp: uint64(now.UnixMilli()), Side: side, Snapshot: makeSnapshot(1, side == 1)}
+ event := popularityEvent(t, s, "alice", fmt.Sprintf("registration-%d", side), "pvp.popularity", update)
+ if e := s.consumePVP(t.Context(), event); e != nil {
+ t.Fatal(e)
+ }
+ if e := s.consumePVP(t.Context(), event); e != nil {
+ t.Fatal(e)
+ }
+ }
+ if rows := popularityRows(t, s, "/PopularCostumeInfo", now, 0, 0, 0, 1, 0); len(rows) != 0 {
+ t.Fatal("unpublished initial registrations were exposed")
+ }
+ published := now.Add(time.Minute)
+ if e := s.refreshPopularity(t.Context(), published); e != nil {
+ t.Fatal(e)
+ }
+ for _, q := range []struct{ side, order, want uint64 }{{0, 0, 101}, {0, 1, 102}, {1, 0, 102}, {1, 1, 101}} {
+ rows := popularityRows(t, s, "/PopularCostumeInfo", published, 0, q.side, q.order, 1, 0)
+ if len(rows) != 1 || popularityScalar(t, rows[0], 1) != q.want || popularityScalar(t, rows[0], 2) != 1 {
+ t.Fatalf("side=%d order=%d wanted costume %d once: %x", q.side, q.order, q.want, rows)
+ }
+ }
+ update := pvp.PopularityPublished{Timestamp: uint64(published.Add(time.Second).UnixMilli()), Side: 0, Snapshot: makeSnapshot(2, true)}
+ if e := s.consumePVP(t.Context(), popularityEvent(t, s, "alice", "changed-registration", "pvp.popularity", update)); e != nil {
+ t.Fatal(e)
+ }
+ rows := popularityRows(t, s, "/PopularCostumeInfo", published, 0, 0, 0, 1, 0)
+ if len(rows) != 1 || popularityScalar(t, rows[0], 1) != 101 {
+ t.Fatalf("in-period registration change leaked into published statistics: %x", rows)
+ }
+ published = published.Add(7 * 24 * time.Hour)
+ if e := s.refreshPopularity(t.Context(), published); e != nil {
+ t.Fatal(e)
+ }
+ rows = popularityRows(t, s, "/PopularCostumeInfo", published, 0, 0, 0, 1, 0)
+ if len(rows) != 2 || popularityScalar(t, rows[0], 1) != 101 || popularityScalar(t, rows[0], 2) != 0 || popularityScalar(t, rows[0], 3) != 1 || popularityScalar(t, rows[1], 1) != 102 || popularityScalar(t, rows[1], 2) != 1 || popularityScalar(t, rows[1], 3) != 0 {
+ t.Fatalf("weekly publication/history did not shift independently: %x", rows)
+ }
+}
+
+func TestTotalWarPopularityUsesActualCommunityRanking(t *testing.T) {
+ s, _ := popularityFixture(t)
+ now := time.Date(2026, 10, 17, 10, 0, 0, 0, time.UTC)
+ publish := func(owner, score, costume uint64, at time.Time, id string) {
+ t.Helper()
+ p := deck.PopularityPublication{CompletedAt: uint64(at.UnixMilli()), Score: score, OwnerIndex: owner, TotalWarCostumes: []uint64{costume}}
+ event := popularityEvent(t, s, fmt.Sprint(owner), id, deck.PopularityTopic, p)
+ if e := s.consumePopularity(t.Context(), event); e != nil {
+ t.Fatal(e)
+ }
+ if e := s.consumePopularity(t.Context(), event); e != nil {
+ t.Fatal(e)
+ }
+ }
+ publish(1, 999, 101, now, "best-run")
+ if rows := popularityRows(t, s, "/PopularCostumeInfo", now, 3, 0, 0, 0, 0); len(rows) != 0 {
+ t.Fatal("unpublished first result was exposed")
+ }
+ first := now.Add(7 * 24 * time.Hour)
+ if e := s.refreshPopularity(t.Context(), first); e != nil {
+ t.Fatal(e)
+ }
+ if rows := popularityRows(t, s, "/PopularCostumeInfo", first, 3, 0, 0, 0, 0); len(rows) != 0 {
+ t.Fatal("one account cannot claim a top-ten-percent rank")
+ }
+ for owner := uint64(2); owner <= 10; owner++ {
+ publish(owner, 1000-owner, 102, first.Add(time.Hour), "best-run")
+ }
+ if rows := popularityRows(t, s, "/PopularCostumeInfo", first, 3, 0, 0, 0, 0); len(rows) != 0 {
+ t.Fatal("in-period population change bypassed weekly publication")
+ }
+ second := first.Add(7 * 24 * time.Hour)
+ if e := s.refreshPopularity(t.Context(), second); e != nil {
+ t.Fatal(e)
+ }
+ rows := popularityRows(t, s, "/PopularCostumeInfo", second, 3, 0, 0, 0, 0)
+ if len(rows) != 1 || popularityScalar(t, rows[0], 1) != 101 || popularityScalar(t, rows[0], 2) != 1 {
+ t.Fatalf("expected one actual top-ten-percent result: %x", rows)
+ }
+ publish(2, 2000, 102, second.Add(time.Minute), "new-best")
+ rows = popularityRows(t, s, "/PopularCostumeInfo", second, 3, 0, 0, 0, 0)
+ if len(rows) != 1 || popularityScalar(t, rows[0], 1) != 101 {
+ t.Fatalf("new score leaked before the weekly boundary: %x", rows)
+ }
+ third := second.Add(7 * 24 * time.Hour)
+ if e := s.refreshPopularity(t.Context(), third); e != nil {
+ t.Fatal(e)
+ }
+ rows = popularityRows(t, s, "/PopularCostumeInfo", third, 3, 0, 0, 0, 0)
+ if len(rows) != 2 || popularityScalar(t, rows[0], 1) != 101 || popularityScalar(t, rows[0], 2) != 0 || popularityScalar(t, rows[0], 3) != 1 || popularityScalar(t, rows[1], 1) != 102 || popularityScalar(t, rows[1], 2) != 1 || popularityScalar(t, rows[1], 3) != 0 {
+ t.Fatalf("published ranking/history did not move at the weekly boundary: %x", rows)
+ }
+}
diff --git a/go/internal/server/app/shared_pvp.go b/go/internal/server/app/shared_pvp.go
index 92b3e68..cd3601b 100644
--- a/go/internal/server/app/shared_pvp.go
+++ b/go/internal/server/app/shared_pvp.go
@@ -4,8 +4,13 @@ import (
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/battle/pvp"
"bd2server/internal/server/domain/ranking"
+ "bd2server/internal/server/domain/roster/deck"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/outbox"
"bd2server/internal/server/storage/shared"
"context"
+ "encoding/json"
+ "fmt"
)
type rankingStore struct{ store *shared.Store }
@@ -31,3 +36,126 @@ func (t rankingTx) Scan(bucket, prefix, after string, limit int) ([]ranking.Entr
func newSharedPVP(ctx context.Context, store *shared.Store, design *gamedata.PvpDesign, seasons []pvp.Season) (*ranking.PVP, error) {
return ranking.NewPVP(ctx, rankingStore{store}, design, seasons)
}
+
+func (s *sharedRuntime) consumePVP(ctx context.Context, event outbox.Pending) error {
+ if event.Envelope.Event.Topic != "pvp.popularity" {
+ if e := s.pvp.Consume(ctx, event.Envelope.Source, event.Envelope.Event); e != nil {
+ return e
+ }
+ if event.Envelope.Event.Topic == "pvp.battle.settled" && s.statistics != nil {
+ var battle pvp.BattleSettled
+ if e := json.Unmarshal(event.Envelope.Event.Payload, &battle); e != nil {
+ return e
+ }
+ if battle.Mode != pvp.Mirror {
+ return nil
+ }
+ return s.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
+ for side, snapshot := range []pvp.PublishedSnapshot{battle.Attacker, battle.Defender} {
+ if e := s.applyPVPPopularity(tx, snapshot.Profile.OwnerID, pvp.PopularityPublished{Timestamp: battle.Timestamp, Side: uint64(side), Snapshot: snapshot}); e != nil {
+ return e
+ }
+ }
+ return nil
+ })
+ }
+ return nil
+ }
+ var update pvp.PopularityPublished
+ if json.Unmarshal(event.Envelope.Event.Payload, &update) != nil || update.Timestamp == 0 || update.Side > 1 || update.Snapshot.Profile.OwnerID != event.Envelope.Source {
+ return fmt.Errorf("invalid PvP popularity publication")
+ }
+ if s.statistics == nil {
+ return fmt.Errorf("missing popularity design")
+ }
+ if update.Snapshot.Mode != pvp.Mirror {
+ return nil
+ }
+ return s.store.Consume(ctx, event, func(tx *shared.Tx, envelope outbox.Envelope) error {
+ return s.applyPVPPopularity(tx, envelope.Source, update)
+ })
+}
+
+func (s *sharedRuntime) applyPVPPopularity(tx *shared.Tx, owner string, update pvp.PopularityPublished) error {
+ id, e := s.pvp.PopularityRank(update.Snapshot)
+ if e != nil {
+ return e
+ }
+ group := s.statistics.PVPRankGroups[id]
+ if e := rotatePopularity(tx, update.Timestamp); e != nil {
+ return e
+ }
+ source := recommendationSource(owner)
+ identity := fmt.Sprintf("pvp:%s:%d", source, update.Side)
+ raw, found, e := tx.Get("popularity_pvp_revision", fmt.Sprintf("%s:%d", identity, update.Snapshot.Season))
+ if e != nil {
+ return e
+ }
+ var latest uint64
+ if found && json.Unmarshal(raw, &latest) != nil {
+ return fmt.Errorf("invalid PvP popularity revision")
+ }
+ if latest > update.Snapshot.Version {
+ return nil
+ }
+ next := map[string]int64{}
+ costumes := map[uint64]uint64{}
+ if e = wire.Walk(update.Snapshot.Snapshot.FullDeck, func(f wire.Field) error {
+ if f.Number != 3 {
+ return nil
+ }
+ index, _, e := wire.Varint(f.Value, 1)
+ if e != nil {
+ return e
+ }
+ id, _, e := wire.Varint(f.Value, 2)
+ costumes[index] = id
+ return e
+ }); e != nil {
+ return e
+ }
+ if group != 0 && group <= s.statistics.PVPMinimumGroup {
+ if e = wire.Walk(update.Snapshot.Snapshot.FullDeck, func(f wire.Field) error {
+ if f.Number != 1 {
+ return nil
+ }
+ order := uint64(0)
+ return wire.Walk(f.Value, func(skill wire.Field) error {
+ if skill.Number != 5 {
+ return nil
+ }
+ index, _, e := wire.Varint(skill.Value, 1)
+ if e != nil {
+ return e
+ }
+ costume := costumes[index]
+ if costume == 0 {
+ return fmt.Errorf("invalid PvP popularity costume")
+ }
+ for _, filter := range []uint64{0, group} {
+ key := "pvp:" + popularityContext(0, update.Side, order, filter, 0) + fmt.Sprintf("%010d", costume)
+ next[key]++
+ }
+ order++
+ return nil
+ })
+ }); e != nil {
+ return e
+ }
+ }
+ if e = popularityReplace(tx, identity, next); e != nil {
+ return e
+ }
+ raw, e = json.Marshal(update.Snapshot.Version)
+ if e != nil {
+ return e
+ }
+ if e = tx.Put("popularity_pvp_revision", fmt.Sprintf("%s:%d", identity, update.Snapshot.Season), raw); e != nil {
+ return e
+ }
+ r := deck.RecommendRecord{}
+ if e = decodePopularityEquipment(update.Snapshot.Snapshot.FullDeck, &r); e != nil {
+ return e
+ }
+ return s.equipmentPopularity(tx, source, &r)
+}
diff --git a/go/internal/server/app/shared_recommendation.go b/go/internal/server/app/shared_recommendation.go
index 0adb307..3d12b59 100644
--- a/go/internal/server/app/shared_recommendation.go
+++ b/go/internal/server/app/shared_recommendation.go
@@ -61,6 +61,17 @@ func (s *sharedRuntime) consumeRecommendation(ctx context.Context, event outbox.
return e
}
}
+ if s.statistics != nil && update.Revision > previous.Revision {
+ var record *deck.RecommendRecord
+ if update.Public {
+ record = update.Record
+ }
+ if record != nil || !update.Public {
+ if e = s.equipmentPopularity(tx, source, record); e != nil {
+ return e
+ }
+ }
+ }
if update.Record == nil {
return nil
}
diff --git a/go/internal/server/app/shared_runtime.go b/go/internal/server/app/shared_runtime.go
index b45f2c2..ba1cd16 100644
--- a/go/internal/server/app/shared_runtime.go
+++ b/go/internal/server/app/shared_runtime.go
@@ -11,6 +11,7 @@ import (
"sync/atomic"
"time"
+ "bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/ranking"
"bd2server/internal/server/domain/social"
"bd2server/internal/server/runtime/delivery"
@@ -20,11 +21,14 @@ import (
)
type sharedRuntime struct {
+ statistics *gamedata.CollectionStatisticsDesign
directory *publicDirectory
rooms *roomResults
store *shared.Store
pvp *ranking.PVP
huntRanks *ranking.MonsterHunt
+ castleRanks *ranking.Castle
+ rogueRanks *ranking.RogueLike
arcadeRanks *ranking.Arcade
guild *social.Owner
friends *social.Friends
@@ -46,6 +50,14 @@ func openSharedRuntime(ctx context.Context, c *configuration, design *designCata
if err != nil {
return nil, errors.Join(err, store.Close())
}
+ castleRanks, err := ranking.NewCastle(ctx, rankingStore{store})
+ if err != nil {
+ return nil, errors.Join(err, store.Close())
+ }
+ rogueRanks, err := ranking.NewRogueLike(ctx, rankingStore{store})
+ if err != nil {
+ return nil, errors.Join(err, store.Close())
+ }
arcadeRanks, err := ranking.NewArcade(ctx, rankingStore{store})
if err != nil {
return nil, errors.Join(err, store.Close())
@@ -66,7 +78,7 @@ func openSharedRuntime(ctx context.Context, c *configuration, design *designCata
if err != nil {
return nil, errors.Join(err, store.Close())
}
- return &sharedRuntime{store: store, pvp: pvp, huntRanks: huntRanks, arcadeRanks: arcadeRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
+ return &sharedRuntime{statistics: design.collectionStatistics, store: store, pvp: pvp, huntRanks: huntRanks, castleRanks: castleRanks, rogueRanks: rogueRanks, arcadeRanks: arcadeRanks, guild: guild, friends: friends, rooms: rooms, directory: directory}, nil
}
func (s *sharedRuntime) wake(account string) {
@@ -79,6 +91,12 @@ func (s *sharedRuntime) Consume(ctx context.Context, event outbox.Pending) error
if _, _, err := outbox.Validate(event); err != nil {
return err
}
+ if event.Envelope.Event.Topic == "roguelike.ranking" {
+ return s.consumeRogueRanking(ctx, event)
+ }
+ if event.Envelope.Event.Topic == "castle.ranking" {
+ return s.consumeCastleRanking(ctx, event)
+ }
if event.Envelope.Event.Topic == "monster_hunt.ranking" {
return s.consumeHuntRanking(ctx, event)
}
@@ -88,6 +106,9 @@ func (s *sharedRuntime) Consume(ctx context.Context, event outbox.Pending) error
if event.Envelope.Event.Topic == "deck.recommendation" {
return s.consumeRecommendation(ctx, event)
}
+ if event.Envelope.Event.Topic == "deck.popularity" {
+ return s.consumePopularity(ctx, event)
+ }
if event.Envelope.Event.Topic == "arcade.ranking" {
return s.consumeArcadeRanking(ctx, event)
}
@@ -114,7 +135,7 @@ func (s *sharedRuntime) Consume(ctx context.Context, event outbox.Pending) error
return s.rooms.Consume(ctx, event)
}
if strings.HasPrefix(event.Envelope.Event.Topic, "pvp.") {
- return s.pvp.Consume(ctx, event.Envelope.Source, event.Envelope.Event)
+ return s.consumePVP(ctx, event)
}
if event.Envelope.Event.Topic == "social.confirm" {
var proof social.CommitProof
@@ -179,6 +200,9 @@ func (s *sharedRuntime) stop() error {
}
func (s *sharedRuntime) settle(ctx context.Context, registry *playerRegistry, discovery outboxDiscovery) error {
+ if err := s.refreshPopularity(ctx, time.Now()); err != nil {
+ return err
+ }
if err := s.closeExpiredRaids(ctx, registry); err != nil {
return err
}
diff --git a/go/internal/server/app/spine_recordings.go b/go/internal/server/app/spine_recordings.go
new file mode 100644
index 0000000..c186120
--- /dev/null
+++ b/go/internal/server/app/spine_recordings.go
@@ -0,0 +1,101 @@
+package app
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/runtime/player"
+ "bd2server/internal/server/storage/stateio"
+)
+
+const spineRecordingPath = "/client/spine-recordings/"
+
+type spineRecordingDownload struct {
+ ID uint64 `json:"id"`
+ Token string `json:"token"`
+}
+
+func (p *playerAssembly) interactionRecords() roster.InteractionRecordService {
+ return roster.InteractionRecordService{
+ Store: stateio.RootStore{}, Design: p.design.interaction,
+ Authorize: p.interactionAvailable, CheckText: p.checkProfileText,
+ RecordDataURL: func(ctx command.Context, id uint64, token string) (string, error) {
+ if ctx.AccountID == "" {
+ return "", errors.New("recording account identity is missing")
+ }
+ account := base64.RawURLEncoding.EncodeToString([]byte(ctx.AccountID))
+ base := p.options.gameRules.SpineRecording.DownloadBaseURL
+ if base == "" {
+ base = strings.TrimRight(consoleOrigin(p.options), "/") + strings.TrimRight(spineRecordingPath, "/")
+ }
+ return strings.TrimRight(base, "/") + "/" + account + "/" + strconv.FormatUint(id, 10) + "/" + token, nil
+ },
+ }
+}
+
+type spineRecordings struct{ players *playerRegistry }
+
+func (h spineRecordings) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "private, no-store")
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ if r.Method != http.MethodGet && r.Method != http.MethodHead {
+ w.Header().Set("Allow", "GET, HEAD")
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ parts := strings.Split(strings.TrimPrefix(r.URL.Path, spineRecordingPath), "/")
+ if !strings.HasPrefix(r.URL.Path, spineRecordingPath) || len(parts) != 3 || len(parts[0]) > 512 || len(parts[2]) != 43 {
+ http.NotFound(w, r)
+ return
+ }
+ account, err := base64.RawURLEncoding.DecodeString(parts[0])
+ if err != nil || len(account) == 0 || !utf8.Valid(account) || base64.RawURLEncoding.EncodeToString(account) != parts[0] {
+ http.NotFound(w, r)
+ return
+ }
+ id, err := strconv.ParseUint(parts[1], 10, 63)
+ if err != nil || id == 0 || strconv.FormatUint(id, 10) != parts[1] {
+ http.NotFound(w, r)
+ return
+ }
+ if token, err := base64.RawURLEncoding.DecodeString(parts[2]); err != nil || len(token) != 32 || base64.RawURLEncoding.EncodeToString(token) != parts[2] {
+ http.NotFound(w, r)
+ return
+ }
+ statePath := filepath.Join(h.players.factory.options.stateDirectory, "accounts", accountDirectoryName(string(account)), "state.db")
+ if _, err := os.Stat(statePath); errors.Is(err, os.ErrNotExist) {
+ http.NotFound(w, r)
+ return
+ } else if err != nil {
+ http.Error(w, "recording unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ request, err := json.Marshal(spineRecordingDownload{ID: id, Token: parts[2]})
+ if err != nil {
+ http.Error(w, "recording unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ body, err := executePlayerSystem(r.Context(), h.players, string(account), player.ReadSpineRecording, request)
+ if errors.Is(err, roster.ErrRecordNotFound) {
+ http.NotFound(w, r)
+ return
+ }
+ if err != nil {
+ http.Error(w, "recording unavailable", http.StatusServiceUnavailable)
+ return
+ }
+ w.Header().Set("Content-Type", "application/octet-stream")
+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))
+ if r.Method == http.MethodGet {
+ _, _ = w.Write(body)
+ }
+}
diff --git a/go/internal/server/app/spine_recordings_integration_test.go b/go/internal/server/app/spine_recordings_integration_test.go
new file mode 100644
index 0000000..6ec5b07
--- /dev/null
+++ b/go/internal/server/app/spine_recordings_integration_test.go
@@ -0,0 +1,177 @@
+//go:build integration
+
+package app
+
+import (
+ "bytes"
+ "compress/gzip"
+ "context"
+ "encoding/binary"
+ "hash/crc32"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "bd2server/internal/server/design/gameconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/gateway/transport"
+)
+
+// This encodes the 2.36.7 client's RecordData.Serialize/Compress format,
+// independently of the server parser: click events on prestige illustration
+// 1065193, point 1/1, tool 0 from GameData 20261012190548.
+func nativeInteractionRecording(t *testing.T, delays ...int32) []byte {
+ t.Helper()
+ raw := binary.LittleEndian.AppendUint32(nil, uint32(len(delays)))
+ for _, delay := range delays {
+ raw = append(raw, 1)
+ for _, value := range []int32{delay, 1, 1, 0} {
+ raw = binary.AppendUvarint(raw, uint64(uint32(value<<1)^uint32(value>>31)))
+ }
+ }
+ var compressed bytes.Buffer
+ gz := gzip.NewWriter(&compressed)
+ if _, err := gz.Write(raw); err != nil {
+ t.Fatal(err)
+ }
+ if err := gz.Close(); err != nil {
+ t.Fatal(err)
+ }
+ out := binary.LittleEndian.AppendUint32(nil, crc32.ChecksumIEEE(raw))
+ return append(append(out, 1), compressed.Bytes()...)
+}
+
+func TestInteractionRecordingPersistsNativePlaybackAndRevokesReplacedData(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ for _, account := range accounts {
+ s := &trapPlayerScenario{factory: factory, account: account, owner: openNicknamePlayer(t, factory, account)}
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ if _, err := p.ownedItems.GrantOnce(ctx, "recording-illustration", []gamedata.BattleReward{{Type: 45, ID: 65193, Count: 1}}); err != nil {
+ t.Fatal(err)
+ }
+ })
+ closeNicknamePlayer(t, s.owner)
+ }
+ registry := newPlayerRegistry(factory, time.Minute)
+ t.Cleanup(func() {
+ if err := registry.Close(context.Background()); err != nil {
+ t.Error(err)
+ }
+ })
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ r.URL.Path = strings.Replace(r.URL.Path, "/replay/", spineRecordingPath, 1)
+ transport.HTTP{SpineRecordings: spineRecordings{players: registry}}.Handler().ServeHTTP(w, r)
+ }))
+ defer server.Close()
+ configured, err := gameconfig.Document.Parse([]byte(`{"schema_version":1,"spine_recording":{"download_base_url":"` + server.URL + `/replay"}}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ factory.options.gameRules.SpineRecording = configured.SpineRecording
+ a, b := friendHTTPLogin(t, registry, accounts[0]), friendHTTPLogin(t, registry, accounts[1])
+ reject := func(client *friendHTTPClient, path string, fields []byte) {
+ t.Helper()
+ client.seq++
+ body := nicknameEncrypt(t, append(appScalar(1, client.seq), fields...), client.key)
+ request := httptest.NewRequest(http.MethodPut, "/game"+path, bytes.NewReader(body))
+ request.Header.Set("Cookie", client.cookie)
+ response := httptest.NewRecorder()
+ client.handler.ServeHTTP(response, request)
+ if response.Code != http.StatusBadRequest {
+ t.Fatalf("%s accepted invalid recording operation: HTTP%d", path, response.Code)
+ }
+ }
+ download := func(address string, status int, want []byte) {
+ t.Helper()
+ response, err := server.Client().Get(address)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = response.Body.Close() }()
+ body, err := io.ReadAll(response.Body)
+ if err != nil || response.StatusCode != status || status == http.StatusOK && !bytes.Equal(body, want) {
+ t.Fatalf("native playback download: status=%d want=%d bytes=%d error=%v", response.StatusCode, status, len(body), err)
+ }
+ }
+ data := nativeInteractionRecording(t, 250)
+ save := append(appScalar(2, 1065193), appMessage(3, data)...)
+ beforeAchievements := a.send("/SpineInteractionAchievementInfo", nil, 532, 0)
+ beforeRewards := a.send("/SpineInteractionRewardInfo", nil, 548, 0)
+ reject(a, "/SpineInteractionRecordSave", append(appScalar(2, 1065193), appMessage(3, nativeInteractionRecording(t, 601000))...))
+ saved := a.send("/SpineInteractionRecordSave", save, 573, 0)
+ index, address := appValue(saved, 1), nicknameField(t, saved, 3)
+ if index == 0 || nicknameField(t, saved, 2) == "" || !strings.HasPrefix(address, server.URL+"/replay/") {
+ t.Fatal("save did not provide a usable native slot and configured playback address")
+ }
+ a.seq--
+ if retry := a.send("/SpineInteractionRecordSave", save, 573, 0); !bytes.Equal(retry, saved) {
+ t.Fatal("retry allocated another recording or changed the playback address")
+ }
+ list := appRows(a.send("/SpineInteractionRecordInfo", nil, 571, 0), 1)
+ if len(list) != 1 || appValue(list[0], 1) != index || appValue(list[0], 2) != 1065193 || nicknameField(t, list[0], 4) != address {
+ t.Fatal("saved recording cannot be selected in the native list")
+ }
+ download(address, http.StatusOK, data)
+ if details := appRows(a.send("/SpineInteractionRecordDetailInfo", appScalar(2, index), 572, 0), 1); len(details) != 1 || !bytes.Equal(details[0], data) {
+ t.Fatal("design-client playback differs from normal HTTP playback")
+ }
+ if rows := appRows(b.send("/SpineInteractionRecordInfo", nil, 571, 0), 1); len(rows) != 0 {
+ t.Fatal("recording list leaked another player's recordings")
+ }
+ reject(b, "/SpineInteractionRecordNameUpdate", append(appScalar(2, index), appMessage(3, []byte("ForeignName"))...))
+ otherSaved := b.send("/SpineInteractionRecordSave", save, 573, 0)
+ foreign, err := url.Parse(nicknameField(t, otherSaved, 3))
+ if err != nil {
+ t.Fatal(err)
+ }
+ foreign.Path = foreign.Path[:strings.LastIndexByte(foreign.Path, '/')+1] + address[strings.LastIndexByte(address, '/')+1:]
+ download(foreign.String(), http.StatusNotFound, nil)
+ corrupt := append([]byte(nil), data...)
+ corrupt[0] ^= 1
+ reject(a, "/SpineInteractionRecordDataUpdate", append(appScalar(2, index), appMessage(3, corrupt)...))
+ download(address, http.StatusOK, data)
+ a.send("/SpineInteractionRecordNameUpdate", append(appScalar(2, index), appMessage(3, []byte("我的回放"))...), 576, 0)
+ updatedData := nativeInteractionRecording(t, 250, 500)
+ updated := a.send("/SpineInteractionRecordDataUpdate", append(appScalar(2, index), appMessage(3, updatedData)...), 575, 0)
+ newAddress := nicknameField(t, updated, 1)
+ if newAddress == address {
+ t.Fatal("replacing a recording preserved the previous download capability")
+ }
+ download(address, http.StatusNotFound, nil)
+ download(newAddress, http.StatusOK, updatedData)
+ if err := registry.Close(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ registry = newPlayerRegistry(factory, time.Minute)
+ a = friendHTTPLogin(t, registry, accounts[0])
+ list = appRows(a.send("/SpineInteractionRecordInfo", nil, 571, 0), 1)
+ if len(list) != 1 || nicknameField(t, list[0], 3) != "我的回放" || nicknameField(t, list[0], 4) != newAddress {
+ t.Fatal("server restart lost the renamed recording or its playback link")
+ }
+ download(newAddress, http.StatusOK, updatedData)
+ if !bytes.Equal(a.send("/SpineInteractionAchievementInfo", nil, 532, 0), beforeAchievements) || !bytes.Equal(a.send("/SpineInteractionRewardInfo", nil, 548, 0), beforeRewards) {
+ t.Fatal("recording/replaying incorrectly changed interaction discoveries or reward claims")
+ }
+ for range 3 {
+ a.send("/SpineInteractionRecordSave", save, 573, 0)
+ }
+ reject(a, "/SpineInteractionRecordSave", save)
+ a.send("/SpineInteractionRecordDelete", appScalar(2, index), 574, 0)
+ a.seq--
+ a.send("/SpineInteractionRecordDelete", appScalar(2, index), 574, 0)
+ download(newAddress, http.StatusNotFound, nil)
+ newSave := a.send("/SpineInteractionRecordSave", save, 573, 0)
+ if appValue(newSave, 1) <= index || len(appRows(a.send("/SpineInteractionRecordInfo", nil, 571, 0), 1)) != 4 {
+ t.Fatal("deleting a recording did not release a slot, or reused a deleted recording identity")
+ }
+ if err := registry.Close(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ registry = newPlayerRegistry(factory, time.Minute)
+ download(newAddress, http.StatusNotFound, nil)
+}
diff --git a/go/internal/server/app/story_archive_integration_test.go b/go/internal/server/app/story_archive_integration_test.go
new file mode 100644
index 0000000..2c08c40
--- /dev/null
+++ b/go/internal/server/app/story_archive_integration_test.go
@@ -0,0 +1,102 @@
+//go:build integration
+
+package app
+
+import (
+ "testing"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/world/progress"
+)
+
+func TestStoryArchiveRestoresPlayableChaptersAndSeparateStoryProgress(t *testing.T) {
+ factory, accounts := newIntegrationFactory(t)
+ s := &trapPlayerScenario{factory: factory, account: accounts[0]}
+ s.owner = openNicknamePlayer(t, factory, s.account)
+ t.Cleanup(func() { closeNicknamePlayer(t, s.owner) })
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ for quest := 1; quest <= 46; quest++ {
+ if err := p.progressState.ClearQuest(ctx, quest, 1, 0); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, quest := range []int{101, 102} {
+ if err := p.progressState.ClearQuest(ctx, quest, 1, 0); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := p.progressState.SelectQuest(ctx, 1, progress.QuestSelection{Difficulty: 2}); err != nil {
+ t.Fatal(err)
+ }
+ var tickets []gamedata.BattleReward
+ for _, chapter := range []int{2, 3} {
+ rule := p.design.world.Story.Packs[chapter].Open
+ if rule == nil || rule.TicketID == 0 {
+ t.Fatal("chapter access prerequisite is unavailable")
+ }
+ tickets = append(tickets, gamedata.BattleReward{Type: 19, ID: rule.TicketID, Count: 1})
+ }
+ if _, err := p.ownedItems.GrantOnce(ctx, "archive-chapter-unlock", tickets); err != nil {
+ t.Fatal(err)
+ }
+ if err := p.progressState.ClearQuest(ctx, 1, 2, 0); err != nil {
+ t.Fatal(err)
+ }
+ })
+ chapter3Available := false
+ for _, row := range appRows(s.protocol(t, "/PackInfo", appScalar(1, uint64(s.commands+1))), 1) {
+ if appValue(row, 1) == 3 {
+ chapter3Available = true
+ if appValue(row, 8) != 0 {
+ t.Fatal("archive unlocked a chapter that has never been entered")
+ }
+ }
+ }
+ if !chapter3Available {
+ t.Fatal("chapter 3 access ticket did not make it available")
+ }
+ s.protocol(t, "/PackInGameInfo", trapRequest(uint64(s.commands+1), 3))
+ assertArchive := func() {
+ t.Helper()
+ gold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
+ packInfo := appRows(s.protocol(t, "/PackInfo", appScalar(1, uint64(s.commands+1))), 1)
+ chapter2, chapter3 := false, false
+ for _, row := range packInfo {
+ if appValue(row, 1) == 2 {
+ chapter2 = appValue(row, 8) == 1
+ }
+ if appValue(row, 1) == 3 {
+ chapter3 = appValue(row, 8) == 1
+ }
+ }
+ if !chapter2 || !chapter3 {
+ t.Fatal("story menu locks the free chapter despite satisfied world access")
+ }
+ preview := s.protocol(t, "/PackPreviewInfo", trapRequest(uint64(s.commands+1), 1))
+ got := map[uint64]uint64{}
+ for _, row := range appRows(preview, 2) {
+ got[appValue(row, 1)] = appValue(row, 2)
+ }
+ // Current pack1 QuestTitleTable separates main1..46, side101..112,
+ // and side301..319. StoryListPanel filters replay using each title.
+ if len(got) != 3 || got[1] != 46 || got[2] != 102 || got[3] != 0 {
+ t.Fatalf("replay lost completed story or unlocked an unplayed side story: %v", got)
+ }
+ if s.owner.assembly.wallet.Snapshot(command.Context{}).Gold != gold {
+ t.Fatal("opening the story archive granted a gameplay reward")
+ }
+ }
+ assertArchive()
+ closeNicknamePlayer(t, s.owner)
+ s.owner = openNicknamePlayer(t, factory, s.account)
+ assertArchive()
+ other := &trapPlayerScenario{factory: factory, account: accounts[1]}
+ other.owner = openNicknamePlayer(t, factory, other.account)
+ defer closeNicknamePlayer(t, other.owner)
+ for _, row := range appRows(other.protocol(t, "/PackPreviewInfo", trapRequest(1, 1)), 2) {
+ if appValue(row, 2) != 0 {
+ t.Fatal("a new account inherited completed story replay")
+ }
+ }
+}
diff --git a/go/internal/server/app/story_checkpoint_integration_test.go b/go/internal/server/app/story_checkpoint_integration_test.go
index ab82198..bc88202 100644
--- a/go/internal/server/app/story_checkpoint_integration_test.go
+++ b/go/internal/server/app/story_checkpoint_integration_test.go
@@ -261,14 +261,35 @@ func TestUnfinishedQuestPresentationSurvivesReloadWithoutRewindingRewards(t *tes
})
s.protocol(t, "/PackInGameInfo", trapRequest(1, 5))
s.position(t, 5, 51)
+ assertHighestQuest := func(want uint64) {
+ t.Helper()
+ preview := s.protocol(t, "/PackPreviewInfo", trapRequest(uint64(s.commands+1), 5))
+ story := appRows(preview, 2)
+ if len(story) != 1 || appValue(story[0], 1) != 1 || appValue(story[0], 2) != want {
+ t.Fatalf("story replay frontier did not follow the completed dialogue: %v, want %d", story, want)
+ }
+ rows := appRows(s.protocol(t, "/QuestMaxClearInfo", appScalar(1, uint64(s.commands+1))), 1)
+ for _, row := range rows {
+ if appValue(row, 1) == 5 {
+ if got := appValue(row, 2); got != want {
+ t.Fatalf("client mission unlock frontier=%d, want completed quest %d", got, want)
+ }
+ return
+ }
+ }
+ t.Fatal("client cannot update its quest unlock frontier without a pack row")
+ }
+ assertHighestQuest(25)
beforeGold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold
clear := wire.AppendVarint(trapRequest(2, 26), 3, 5)
s.protocol(t, "/QuestClear", clear)
+ assertHighestQuest(26)
if gold := s.owner.assembly.wallet.Snapshot(command.Context{}).Gold; gold != beforeGold+700 {
t.Fatalf("quest gold=%d want%d", gold, beforeGold+700)
}
closeNicknamePlayer(t, s.owner)
s.owner = openNicknamePlayer(t, factory, s.account)
+ assertHighestQuest(26)
pending := storyCheckpointCall(t, s.owner, "read", world.StoryCheckpoint{}).Checkpoint
if pending == nil || pending.PackID != 5 || pending.QuestID != 26 || pending.Phase != "complete" || pending.Timeline != "Quest_Main_26" || pending.MapID != 51 {
t.Fatalf("unfinished cinema was not restored: %+v", pending)
diff --git a/go/internal/server/app/talent_travel_integration_test.go b/go/internal/server/app/talent_travel_integration_test.go
new file mode 100644
index 0000000..dfed7e8
--- /dev/null
+++ b/go/internal/server/app/talent_travel_integration_test.go
@@ -0,0 +1,167 @@
+//go:build integration
+
+package app
+
+import (
+ "bytes"
+ "testing"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/roster"
+)
+
+// WayPointMakePopupUI sends the destination map through TalentSkillUse, then
+// IUseTalentSkillWaypointMake sends WaypointUse from the map-zero temporary
+// point. Pack2's safe point is1/map21 and its temporary point is7.
+func TestTalentPortalPaysOnceAndAuthorizesOnlyItsSelectedActivatedDestination(t *testing.T) {
+ s := newTrapPlayerScenario(t, 2)
+ s.position(t, 2, 22)
+ var caster, catalyst uint64
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ if _, err := p.collection.GrantCostumes(ctx, "portal-owned-character", []uint64{701}, p.design.rewardCostumes); err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range p.collection.Characters() {
+ if p.design.talentUseDesign.Characters[c.ID].Group == 1505 {
+ c.TalentLevel = 1
+ c.TalentExp = 0
+ if err := p.collection.UpdateCharacter(ctx, c.ID, c); err != nil {
+ t.Fatal(err)
+ }
+ caster = c.InvenIndex
+ }
+ }
+ if caster == 0 {
+ t.Fatal("portal caster not owned")
+ }
+ if err := p.wallet.ExchangeOnce(ctx, "portal-catalyst", nil, []gamedata.Reward{{Type: 12, Count: 100}}); err != nil {
+ t.Fatal(err)
+ }
+ catalyst = p.wallet.Snapshot(ctx).Catalyst
+ })
+ cast := func(seq, mapID uint64) []byte {
+ return append(append(appScalar(1, seq), appScalar(2, caster)...), appScalar(3, mapID)...)
+ }
+ travel := func(seq, destination uint64) []byte {
+ return append(append(append(append(appScalar(1, seq), appScalar(2, 2)...), appScalar(3, 7)...), appScalar(4, destination)...), appScalar(5, 1)...)
+ }
+ assertBalance := func(want uint64) {
+ t.Helper()
+ s.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ if got := p.wallet.Snapshot(ctx).Catalyst; got != want {
+ t.Fatalf("portal catalyst balance got%d want%d", got, want)
+ }
+ })
+ }
+ s.protocol(t, "/WaypointSave", append(append(appScalar(1, 10), appScalar(2, 2)...), appScalar(3, 1)...))
+ s.protocol(t, "/WaypointSave", append(append(appScalar(1, 11), appScalar(2, 2)...), appScalar(3, 2)...))
+ if _, err := s.execute("/WaypointUse", travel(12, 1)); err == nil {
+ t.Fatal("temporary portal worked without a talent cast")
+ }
+ if _, err := s.execute("/TalentSkillUse", cast(13, 22)); err == nil {
+ t.Fatal("novice portal accepted a battle map instead of a safe destination")
+ }
+ if _, err := s.execute("/TalentSkillUse", cast(14, 141)); err == nil {
+ t.Fatal("portal accepted a map belonging to another pack")
+ }
+ assertBalance(catalyst)
+ response := s.protocol(t, "/TalentSkillUse", cast(15, 21))
+ assertBalance(catalyst - 20)
+ s.reopen(t)
+ if replay := s.protocol(t, "/TalentSkillUse", cast(15, 21)); !bytes.Equal(response, replay) {
+ t.Fatal("reopened player lost its acknowledged cast response")
+ }
+ assertBalance(catalyst - 20)
+ if _, err := s.execute("/WaypointUse", travel(16, 2)); err == nil {
+ t.Fatal("portal authorization allowed a different activated destination")
+ }
+ s.protocol(t, "/WaypointUse", travel(17, 1))
+ s.reopen(t)
+ s.protocol(t, "/WaypointUse", travel(17, 1))
+ if _, err := s.execute("/WaypointUse", travel(17, 2)); err == nil {
+ t.Fatal("travel retry changed the authorized destination")
+ }
+ if _, err := s.execute("/WaypointUse", travel(18, 1)); err == nil {
+ t.Fatal("one portal cast authorized a second journey")
+ }
+ assertBalance(catalyst - 20)
+ s.position(t, 2, 21)
+ s.reopen(t)
+ s.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ pack, mapID, _, err := p.worldService.TalentFieldContext(ctx)
+ if err != nil || pack != 2 || mapID != 21 {
+ t.Fatalf("native post-warp position not restored: pack%d map%d err%v", pack, mapID, err)
+ }
+ c, found := p.worldService.CharacterService().Find(ctx, caster)
+ if !found || c.TalentExp != 1 {
+ t.Fatal("portal replay duplicated or lost earned talent experience")
+ }
+ })
+}
+
+// RecvTalentSkillUpgradeResponse resets Overwhelm's shared UseCount. Current
+// group305 needs10 EXP and one type8/id3 book plus1000 gold for its first upgrade.
+func TestOverwhelmUpgradeRestoresSpentUsesAfterReopening(t *testing.T) {
+ s := newTrapPlayerScenario(t, 2)
+ s.position(t, 2, 22)
+ var caster uint64
+ var book []byte
+ s.run(t, true, func(ctx command.Context, p *playerAssembly) {
+ if _, err := p.collection.GrantCostumes(ctx, "overwhelm-owned-character", []uint64{1101}, p.design.rewardCostumes); err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range p.collection.Characters() {
+ if p.design.talentUseDesign.Characters[c.ID].Group == 305 {
+ c.TalentLevel, c.TalentExp = 1, 9
+ if err := p.collection.UpdateCharacter(ctx, c.ID, c); err != nil {
+ t.Fatal(err)
+ }
+ caster = c.InvenIndex
+ }
+ }
+ if caster == 0 {
+ t.Fatal("overwhelm caster not owned")
+ }
+ if err := p.wallet.ExchangeOnce(ctx, "overwhelm-resources", nil, []gamedata.Reward{{Type: 12, Count: 200}, {Type: 4, Count: 2000}}); err != nil {
+ t.Fatal(err)
+ }
+ items, err := p.ownedItems.GrantOnce(ctx, "overwhelm-upgrade-book", []gamedata.BattleReward{{Type: 8, ID: 3, Count: 1}})
+ if err != nil || len(items) != 1 {
+ t.Fatalf("upgrade book fixture: %v", err)
+ }
+ book = inventoryItem(items[0].InvenIndex, 3, 8, 1)
+ })
+ cast := append(appScalar(1, 20), appScalar(2, caster)...)
+ result := s.protocol(t, "/TalentSkillUse", cast)
+ if rows := appRows(result, 1); len(rows) != 1 || appValue(rows[0], 4) != 1 {
+ t.Fatal("cast did not consume an overwhelm use")
+ }
+ upgrade := append(append(append(appScalar(1, 21), appScalar(2, caster)...), appMessage(3, book)...), appMessage(3, inventoryItem(0, 0, 4, 1000))...)
+ s.protocol(t, "/TalentSkillUpgrade", upgrade)
+ s.reopen(t)
+ s.run(t, false, func(ctx command.Context, p *playerAssembly) {
+ var c roster.Character
+ c, _ = p.worldService.CharacterService().Find(ctx, caster)
+ if c.TalentLevel != 2 || c.TalentExp != 10 {
+ t.Fatalf("earned first upgrade not persisted: level%d EXP%d", c.TalentLevel, c.TalentExp)
+ }
+ info, err := p.talentUseService.PackInfo(ctx, 2)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, row := range appRows(info, 13) {
+ if appValue(row, 1) == 305 {
+ if appValue(row, 4) != 0 {
+ t.Fatal("upgraded overwhelm retained its spent uses")
+ }
+ return
+ }
+ }
+ t.Fatal("upgraded overwhelm usage absent")
+ })
+ result = s.protocol(t, "/TalentSkillUse", append(appScalar(1, 22), appScalar(2, caster)...))
+ if rows := appRows(result, 1); len(rows) != 1 || appValue(rows[0], 4) != 1 {
+ t.Fatal("first cast after upgrading did not start from restored uses")
+ }
+}
diff --git a/go/internal/server/design/gameconfig/config.go b/go/internal/server/design/gameconfig/config.go
index 47d92cc..43c269f 100644
--- a/go/internal/server/design/gameconfig/config.go
+++ b/go/internal/server/design/gameconfig/config.go
@@ -19,6 +19,7 @@ type Config struct {
Story StoryConfig `json:"story"`
Purchases PurchasesConfig `json:"purchases"`
TextModeration TextModerationConfig `json:"text_moderation"`
+ SpineRecording SpineRecordingConfig `json:"spine_recording"`
}
type TextModerationConfig struct {
@@ -42,6 +43,7 @@ var TextScopes = []string{
"nickname", "greeting", "master_title", "preset_name", "equipment_preset_name", "equipment_mark",
"monster_hunt_preset_name", "guild_raid_preset_name", "colosseum_preset_name",
"guild_name", "guild_message", "guild_notice", "room_name", "chat",
+ "spine_record_name",
}
func DefaultTextModeration() TextModerationConfig {
@@ -141,6 +143,7 @@ var Document = commonconfig.Document[Config]{
var problems commonconfig.Problems
realtimeRules(c.Realtime, &problems)
textModerationRules(c.TextModeration, &problems)
+ spineRecordingRules(c.SpineRecording, &problems)
return problems
},
Advice: func(c Config, path string) commonconfig.Problems {
diff --git a/go/internal/server/design/gameconfig/schema.go b/go/internal/server/design/gameconfig/schema.go
index e4682a1..eb8993f 100644
--- a/go/internal/server/design/gameconfig/schema.go
+++ b/go/internal/server/design/gameconfig/schema.go
@@ -16,6 +16,10 @@ var schema = commonconfig.Schema{
Title: "游戏规则",
Summary: "服务端统一的玩法规则。修改后重启服务端生效。",
Sections: []commonconfig.Section{
+ {ID: "spine_recording", Title: "互动录制", Help: "保存玩家的互动立绘操作记录,并供原生客户端回放。修改后重启服务端生效。", Fields: []commonconfig.Field{
+ {Path: "spine_recording.download_base_url", Kind: commonconfig.KindString, Label: "录制下载基础 URL", Format: "url", Placeholder: "https://game.example.com/client/spine-recordings",
+ Help: "留空使用本服地址。自定义地址须反向代理到本服的 /client/spine-recordings/;系统会在其后追加录制路径和访问凭据。公网须使用 HTTPS。"},
+ }},
{ID: "story", Title: "开局章节", Help: "首次成功初始化后永久保存在服务器状态中,之后不能更改;不能通过删除数据库切换开局。", Fields: []commonconfig.Field{
{Path: "story.start_pack_id", Kind: commonconfig.KindInteger, Label: "起始章节", Options: []commonconfig.Option{
{Value: 21, Label: "店长篇", Help: "当前客户端默认的开局,使用该篇的任务和教学流程。"},
diff --git a/go/internal/server/design/gameconfig/spine_recording.go b/go/internal/server/design/gameconfig/spine_recording.go
new file mode 100644
index 0000000..993e82f
--- /dev/null
+++ b/go/internal/server/design/gameconfig/spine_recording.go
@@ -0,0 +1,29 @@
+package gameconfig
+
+import (
+ "net"
+ "net/url"
+ "strings"
+
+ commonconfig "bd2server/internal/common/config"
+)
+
+type SpineRecordingConfig struct {
+ DownloadBaseURL string `json:"download_base_url"`
+}
+
+func spineRecordingRules(c SpineRecordingConfig, problems *commonconfig.Problems) {
+ if c.DownloadBaseURL == "" {
+ return
+ }
+ u, err := url.Parse(c.DownloadBaseURL)
+ if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" ||
+ (u.Scheme != "http" && u.Scheme != "https") || strings.ContainsAny(c.DownloadBaseURL, " \t\r\n") {
+ problems.Add("spine_recording.download_base_url", commonconfig.RuleFormat, "must be an absolute HTTP(S) URL without credentials, query, or fragment")
+ return
+ }
+ ip := net.ParseIP(u.Hostname())
+ if u.Scheme == "http" && !strings.EqualFold(u.Hostname(), "localhost") && (ip == nil || !ip.IsLoopback()) {
+ problems.Add("spine_recording.download_base_url", commonconfig.RuleFormat, "must use HTTPS outside loopback development")
+ }
+}
diff --git a/go/internal/server/design/gamedata/cafeteria_dating.go b/go/internal/server/design/gamedata/cafeteria_dating.go
new file mode 100644
index 0000000..538a7ed
--- /dev/null
+++ b/go/internal/server/design/gamedata/cafeteria_dating.go
@@ -0,0 +1,155 @@
+package gamedata
+
+import (
+ "bd2server/internal/server/protocol/wire"
+ "encoding/binary"
+ "fmt"
+ "slices"
+)
+
+// SocialRow contains scalar and repeated integer fields from the current client schema.
+type SocialRow struct{ Fields map[int][]uint64 }
+
+func (r SocialRow) V(n int) uint64 {
+ if v := r.Fields[n]; len(v) > 0 {
+ return v[0]
+ }
+ return 0
+}
+func (r SocialRow) A(n int) []uint64 { return r.Fields[n] }
+
+type SocialTable struct {
+ Rows map[[2]uint64]SocialRow
+ Groups map[uint64][]uint64
+}
+
+func (t SocialTable) Row(group, id uint64) (SocialRow, bool) {
+ r, ok := t.Rows[[2]uint64{group, id}]
+ return r, ok
+}
+func loadSocialTables(root, version string, specs map[string][2]int) (map[string]SocialTable, error) {
+ db, done, e := openStatDatabase(root, version)
+ if e != nil {
+ return nil, e
+ }
+ defer done()
+ out := map[string]SocialTable{}
+ for name, fields := range specs {
+ rows, e := db.Query("SELECT ProtoBuf FROM " + name)
+ if e != nil {
+ return nil, e
+ }
+ table := SocialTable{Rows: map[[2]uint64]SocialRow{}, Groups: map[uint64][]uint64{}}
+ for rows.Next() {
+ var p []byte
+ if e = rows.Scan(&p); e != nil {
+ _ = rows.Close()
+ return nil, e
+ }
+ r := SocialRow{Fields: map[int][]uint64{}}
+ e = wire.Walk(p, func(f wire.Field) error {
+ if f.Type == 0 {
+ v, _ := binary.Uvarint(f.Value)
+ r.Fields[f.Number] = append(r.Fields[f.Number], v)
+ } else if f.Type == 2 && socialPacked(name, f.Number) {
+ p := f.Value
+ for len(p) > 0 {
+ v, n := binary.Uvarint(p)
+ if n <= 0 {
+ return wire.ErrMalformed
+ }
+ r.Fields[f.Number] = append(r.Fields[f.Number], v)
+ p = p[n:]
+ }
+ }
+ return nil
+ })
+ if e != nil {
+ _ = rows.Close()
+ return nil, e
+ }
+ g, id := r.V(fields[0]), r.V(fields[1])
+ if fields[0] == 0 {
+ g = 0
+ }
+ k := [2]uint64{g, id}
+ if _, ok := table.Rows[k]; ok {
+ _ = rows.Close()
+ return nil, fmt.Errorf("%s: duplicate row", name)
+ }
+ table.Rows[k] = r
+ table.Groups[g] = append(table.Groups[g], id)
+ }
+ e = rows.Err()
+ _ = rows.Close()
+ if e != nil {
+ return nil, e
+ }
+ for _, ids := range table.Groups {
+ slices.Sort(ids)
+ }
+ out[name] = table
+ }
+ return out, nil
+}
+func socialPacked(table string, f int) bool {
+ switch table {
+ case "CafeteriaLevelTable":
+ return f >= 8 && f <= 12
+ case "DatingDefaultTable":
+ return f >= 2 && f <= 4
+ case "DatingMessageTable":
+ return f >= 6 && f <= 8
+ case "CafeteriaUniqueNpcSpawnTable":
+ return f == 2 || f == 5
+ }
+ return false
+}
+
+type CafeteriaDesign struct {
+ Default SocialRow
+ Levels, Manage, Costumes, NPCs, Events, Connections, UniqueNPCs SocialTable
+}
+
+func LoadCafeteriaDesign(root, version string) (*CafeteriaDesign, error) {
+ t, e := loadSocialTables(root, version, map[string][2]int{"CafeteriaDefaultTable": {0, 13}, "CafeteriaLevelTable": {0, 5}, "CafeteriaManageTable": {5, 6}, "CafeteriaCostumeTable": {0, 1}, "CafeteriaNpcTable": {0, 2}, "CafeteriaEventTable": {5, 6}, "DatingCostumeTable": {0, 1}, "CafeteriaUniqueNpcSpawnTable": {0, 1}})
+ if e != nil {
+ return nil, e
+ }
+ d := &CafeteriaDesign{Levels: t["CafeteriaLevelTable"], Manage: t["CafeteriaManageTable"], Costumes: t["CafeteriaCostumeTable"], NPCs: t["CafeteriaNpcTable"], Events: t["CafeteriaEventTable"], Connections: t["DatingCostumeTable"], UniqueNPCs: t["CafeteriaUniqueNpcSpawnTable"]}
+ d.Default, _ = t["CafeteriaDefaultTable"].Row(0, 0)
+ if d.Default.V(16) == 0 || len(d.Levels.Rows) == 0 {
+ return nil, fmt.Errorf("cafeteria: missing design")
+ }
+ return d, nil
+}
+
+type DatingDesign struct {
+ Default SocialRow
+ Episodes, Messages, Costumes SocialTable
+ MessageEpisode map[uint64][2]uint64
+ CostumeGroup map[uint64]SocialRow
+}
+
+func LoadDatingDesign(root, version string) (*DatingDesign, error) {
+ t, e := loadSocialTables(root, version, map[string][2]int{"DatingDefaultTable": {0, 6}, "DatingEpisodeTable": {6, 7}, "DatingMessageTable": {1, 2}, "DatingCostumeTable": {0, 4}})
+ if e != nil {
+ return nil, e
+ }
+ d := &DatingDesign{Episodes: t["DatingEpisodeTable"], Messages: t["DatingMessageTable"], Costumes: t["DatingCostumeTable"], MessageEpisode: map[uint64][2]uint64{}, CostumeGroup: map[uint64]SocialRow{}}
+ d.Default, _ = t["DatingDefaultTable"].Row(0, 0)
+ for k, r := range d.Episodes.Rows {
+ for _, f := range []int{2, 3} {
+ if id := r.V(f); id > 0 {
+ d.MessageEpisode[id] = k
+ }
+ }
+ }
+ for _, r := range d.Costumes.Rows {
+ d.CostumeGroup[r.V(2)] = r
+ }
+ if d.Default.V(5) == 0 || len(d.Episodes.Rows) == 0 {
+ return nil, fmt.Errorf("dating: missing design")
+ }
+ return d, nil
+}
diff --git a/go/internal/server/design/gamedata/castle_rewards.go b/go/internal/server/design/gamedata/castle_rewards.go
new file mode 100644
index 0000000..86e5b35
--- /dev/null
+++ b/go/internal/server/design/gamedata/castle_rewards.go
@@ -0,0 +1,372 @@
+package gamedata
+
+import (
+ "database/sql"
+ "fmt"
+ "math"
+ "sort"
+)
+
+type CastleChallenge struct {
+ Type, Value1, Value2, Score uint64
+ Reward Reward
+}
+type CastleDeck struct {
+ ID uint64
+ Challenges []CastleChallenge
+ Rewards []Reward
+}
+type CastleTower struct{ Mode, ID, Previous, Deck uint64 }
+type CastleScoring struct {
+ Base, Turn, Survival, Retry uint64
+ BossMultiplier float64
+}
+type CastleFloor struct {
+ ID, Previous, Boss uint64
+ Monsters map[uint64]uint64
+ Scoring CastleScoring
+ Rewards []Reward
+}
+type ScoreReward struct {
+ ID uint64
+ Score float64
+ Reward Reward
+}
+type CastleRankReward struct {
+ Rank uint64
+ Rewards []Reward
+}
+
+type CastleRewardDesign struct {
+ FloorRanks, TotalRanks []CastleRankReward
+ TotalWarEnemies []TotalWarEnemy
+ TotalWarPresets *PresetDesign
+ PackID uint64
+ Towers map[[2]uint64]CastleTower
+ Floors map[uint64]CastleFloor
+ Decks map[uint64]CastleDeck
+ Daily, TotalWarDaily []ScoreReward
+ Reset FieldResetSchedule
+ Characters map[uint64]CastleCharacter
+}
+type CastleCharacter struct{ Unique, Element uint64 }
+
+func LoadCastleRewardDesign(root, version string) (*CastleRewardDesign, error) {
+ db, done, err := openStatDatabase(root, version)
+ if err != nil {
+ return nil, err
+ }
+ defer done()
+ d := &CastleRewardDesign{Towers: map[[2]uint64]CastleTower{}, Floors: map[uint64]CastleFloor{}, Decks: map[uint64]CastleDeck{}}
+ d.Characters = map[uint64]CastleCharacter{}
+ err = castleRows(db, "CharTable", func(id uint64, raw []byte) error {
+ u, e := optionalScalar(raw, 20)
+ if e != nil {
+ return e
+ }
+ element, e := optionalScalar(raw, 6)
+ if e != nil {
+ return e
+ }
+ d.Characters[id] = CastleCharacter{u, element}
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ rows, err := db.Query("SELECT id,ProtoBuf FROM PackTable ORDER BY id")
+ if err != nil {
+ return nil, err
+ }
+ for rows.Next() {
+ var id uint64
+ var raw []byte
+ if err = rows.Scan(&id, &raw); err != nil {
+ break
+ }
+ var typ uint64
+ typ, err = optionalScalar(raw, 55)
+ if err != nil {
+ break
+ }
+ if typ == 4 {
+ if d.PackID != 0 {
+ err = fmt.Errorf("gamedata: multiple castle packs")
+ break
+ }
+ d.PackID = id
+ }
+ }
+ if err == nil {
+ err = rows.Err()
+ }
+ _ = rows.Close()
+ if err != nil {
+ return nil, err
+ }
+ if d.PackID == 0 {
+ return nil, fmt.Errorf("gamedata: no castle pack")
+ }
+ pack, release, err := OpenDatabase(root, version, fmt.Sprintf("pack%d", d.PackID))
+ if err != nil {
+ return nil, err
+ }
+ defer release()
+ for _, table := range []struct {
+ mode uint64
+ name string
+ }{{16, "EvilCastleGreedTowerTable"}, {19, "EvilCastleRageTowerTable"}, {20, "EvilCastleEnvyTowerTable"}} {
+ var previous uint64
+ err = castleRows(db, table.name, func(id uint64, raw []byte) error {
+ deck, e := optionalScalar(raw, 1)
+ if e != nil {
+ return e
+ }
+ if deck == 0 {
+ return fmt.Errorf("gamedata: empty castle tower deck")
+ }
+ d.Towers[[2]uint64{table.mode, id}] = CastleTower{table.mode, id, previous, deck}
+ previous = id
+ return d.loadDeck(pack, deck)
+ })
+ if err != nil {
+ return nil, err
+ }
+ }
+ var previous uint64
+ err = castleRows(db, "EvilCastleTable", func(id uint64, raw []byte) error {
+ f := CastleFloor{ID: id, Previous: previous, Monsters: map[uint64]uint64{}}
+ previous = id
+ boss, e := optionalScalar(raw, 8)
+ if e != nil {
+ return e
+ }
+ f.Boss = boss
+ ids, e := packedInts(raw, 18)
+ if e != nil {
+ return e
+ }
+ ids = append(ids, boss)
+ for _, monster := range ids {
+ if monster == 0 {
+ continue
+ }
+ var m []byte
+ if e = pack.QueryRow("SELECT ProtoBuf FROM FieldMonsterTable WHERE id=?", monster).Scan(&m); e != nil {
+ return e
+ }
+ decks, e := packedInts(m, 2)
+ if e != nil || len(decks) != 1 {
+ return fmt.Errorf("gamedata: unsupported castle monster decks")
+ }
+ f.Monsters[monster] = decks[0]
+ if e = d.loadDeck(pack, decks[0]); e != nil {
+ return e
+ }
+ }
+ timer, e := optionalScalar(raw, 22)
+ if e != nil {
+ return e
+ }
+ var timing []byte
+ if e = db.QueryRow("SELECT ProtoBuf FROM EvilCastleTimeAttackTable WHERE id=?", timer).Scan(&timing); e != nil {
+ return e
+ }
+ for n, p := range map[int]*uint64{5: &f.Scoring.Base, 10: &f.Scoring.Retry, 11: &f.Scoring.Survival, 12: &f.Scoring.Turn} {
+ *p, e = optionalScalar(timing, n)
+ if e != nil {
+ return e
+ }
+ }
+ f.Scoring.BossMultiplier, _, e = fixed64Double(timing, 6)
+ if e != nil {
+ return e
+ }
+ f.Rewards, e = castleRewards(raw, 4, 3, 2)
+ if e != nil {
+ return e
+ }
+ d.Floors[id] = f
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ for _, item := range []struct {
+ table string
+ dst *[]ScoreReward
+ score, count, id, typ int
+ }{{"EvilCastleDailyRewardTable", &d.Daily, 5, 2, 3, 4}, {"TotalWarRewardTable", &d.TotalWarDaily, 6, 3, 4, 5}} {
+ err = castleRows(db, item.table, func(id uint64, raw []byte) error {
+ r := ScoreReward{ID: id}
+ var e error
+ if item.score == 6 {
+ r.Score, _, e = fixed64Double(raw, item.score)
+ } else {
+ var score uint64
+ score, e = optionalScalar(raw, item.score)
+ r.Score = float64(score)
+ }
+ if e != nil {
+ return e
+ }
+ r.Reward.Type, e = optionalScalar(raw, item.typ)
+ if e != nil {
+ return e
+ }
+ r.Reward.ID, e = optionalScalar(raw, item.id)
+ if e != nil {
+ return e
+ }
+ r.Reward.Count, e = optionalScalar(raw, item.count)
+ if e != nil {
+ return e
+ }
+ if math.IsNaN(r.Score) || math.IsInf(r.Score, 0) || r.Score <= 0 || r.Reward.Type == 0 || r.Reward.Count == 0 {
+ return fmt.Errorf("gamedata: invalid castle daily reward")
+ }
+ *item.dst = append(*item.dst, r)
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ sort.Slice(*item.dst, func(i, j int) bool { return (*item.dst)[i].Score < (*item.dst)[j].Score })
+ }
+ for _, spec := range []struct {
+ table string
+ dst *[]CastleRankReward
+ }{{"EvilCastleRankTable", &d.FloorRanks}, {"EvilCastleTotalRankTable", &d.TotalRanks}} {
+ err = castleRows(db, spec.table, func(_ uint64, raw []byte) error {
+ rank, e := optionalScalar(raw, 6)
+ if e != nil {
+ return e
+ }
+ rewards, e := castleRewards(raw, 3, 2, 1)
+ if e != nil {
+ return e
+ }
+ if rank == 0 {
+ return fmt.Errorf("gamedata: invalid castle reward rank")
+ }
+ *spec.dst = append(*spec.dst, CastleRankReward{rank, rewards})
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ sort.Slice(*spec.dst, func(i, j int) bool { return (*spec.dst)[i].Rank < (*spec.dst)[j].Rank })
+ }
+ d.Reset, err = LoadFieldResetSchedule(root, version)
+ if err != nil {
+ return nil, err
+ }
+ d.TotalWarEnemies, err = loadTotalWarEnemies(root, version)
+ if err != nil {
+ return nil, err
+ }
+ d.TotalWarPresets, err = loadTotalWarPresetDesign(root, version)
+ return d, err
+}
+
+func castleRows(db *sql.DB, table string, visit func(uint64, []byte) error) error {
+ rows, e := db.Query("SELECT id,ProtoBuf FROM " + table + " ORDER BY id")
+ if e != nil {
+ return e
+ }
+ type row struct {
+ id uint64
+ raw []byte
+ }
+ var records []row
+ for rows.Next() {
+ var id uint64
+ var raw []byte
+ if e = rows.Scan(&id, &raw); e != nil {
+ _ = rows.Close()
+ return e
+ }
+ records = append(records, row{id, raw})
+ }
+ e = rows.Err()
+ _ = rows.Close()
+ if e != nil {
+ return e
+ }
+ for _, r := range records {
+ if e = visit(r.id, r.raw); e != nil {
+ return fmt.Errorf("gamedata: %s/%d: %w", table, r.id, e)
+ }
+ }
+ return nil
+}
+func castleRewards(raw []byte, typ, id, count int) ([]Reward, error) {
+ ts, e := packedInts(raw, typ)
+ if e != nil {
+ return nil, e
+ }
+ ids, e := packedInts(raw, id)
+ if e != nil {
+ return nil, e
+ }
+ cs, e := packedInts(raw, count)
+ if e != nil {
+ return nil, e
+ }
+ if len(ts) != len(ids) || len(ts) != len(cs) {
+ return nil, fmt.Errorf("gamedata: castle reward array mismatch")
+ }
+ var out []Reward
+ for i, t := range ts {
+ if t == 0 && ids[i] == 0 && cs[i] == 0 {
+ continue
+ }
+ if t == 0 || cs[i] == 0 {
+ return nil, fmt.Errorf("gamedata: invalid castle reward")
+ }
+ out = append(out, Reward{Type: t, ID: ids[i], Count: cs[i]})
+ }
+ return out, nil
+}
+func (d *CastleRewardDesign) loadDeck(db *sql.DB, id uint64) error {
+ if _, ok := d.Decks[id]; ok {
+ return nil
+ }
+ var raw []byte
+ if e := db.QueryRow("SELECT ProtoBuf FROM BattleDeckTable WHERE id=?", id).Scan(&raw); e != nil {
+ return e
+ }
+ deck := CastleDeck{ID: id}
+ types, e := packedInts(raw, 6)
+ if e != nil {
+ return e
+ }
+ arrays := map[int][]uint64{}
+ for _, n := range []int{7, 8, 9, 10, 11, 12} {
+ arrays[n], e = packedInts(raw, n)
+ if e != nil {
+ return e
+ }
+ if len(arrays[n]) != 0 && len(arrays[n]) != len(types) {
+ return fmt.Errorf("gamedata: castle challenge array mismatch")
+ }
+ }
+ for i, t := range types {
+ if t < 1 || t > 8 {
+ return fmt.Errorf("gamedata: unknown castle challenge type")
+ }
+ c := CastleChallenge{Type: t}
+ for n, p := range map[int]*uint64{7: &c.Value1, 8: &c.Value2, 9: &c.Reward.Count, 10: &c.Reward.ID, 11: &c.Reward.Type, 12: &c.Score} {
+ if len(arrays[n]) > 0 {
+ *p = arrays[n][i]
+ }
+ }
+ deck.Challenges = append(deck.Challenges, c)
+ }
+ deck.Rewards, e = castleRewards(raw, 36, 34, 33)
+ if e != nil {
+ return e
+ }
+ d.Decks[id] = deck
+ return nil
+}
diff --git a/go/internal/server/design/gamedata/collection_statistics.go b/go/internal/server/design/gamedata/collection_statistics.go
new file mode 100644
index 0000000..0212385
--- /dev/null
+++ b/go/internal/server/design/gamedata/collection_statistics.go
@@ -0,0 +1,126 @@
+package gamedata
+
+import "fmt"
+
+type StatisticsCharacter struct{ UniqueID, Grade uint64 }
+type StatisticsEquipment struct{ UniqueID, Slot, Grade, CharacterUniqueID uint64 }
+type CollectionStatisticsDesign struct {
+ Characters map[uint64]StatisticsCharacter
+ CostumeGrade map[uint64]uint64
+ Equipment map[uint64]StatisticsEquipment
+ CastleStages map[uint64]map[uint64]uint64
+ PVPRankGroups map[uint64]uint64
+ PVPMinimumGroup uint64
+ GachaGroups map[uint64]uint64
+}
+
+func LoadCollectionStatistics(root, version string) (*CollectionStatisticsDesign, error) {
+ db, release, err := OpenDatabase(root, version, "common")
+ if err != nil {
+ return nil, err
+ }
+ defer release()
+ d := &CollectionStatisticsDesign{Characters: map[uint64]StatisticsCharacter{}, CostumeGrade: map[uint64]uint64{}, Equipment: map[uint64]StatisticsEquipment{}, CastleStages: map[uint64]map[uint64]uint64{}}
+ uniqueGrade := map[uint64]uint64{}
+ read := func(table string, visit func(uint64, []byte) error) error {
+ rows, e := db.Query("SELECT id,ProtoBuf FROM " + table)
+ if e != nil {
+ return e
+ }
+ defer func() { _ = rows.Close() }()
+ for rows.Next() {
+ var id uint64
+ var b []byte
+ if e = rows.Scan(&id, &b); e != nil {
+ return e
+ }
+ if e = visit(id, b); e != nil {
+ return fmt.Errorf("gamedata: %s %d: %w", table, id, e)
+ }
+ }
+ return rows.Err()
+ }
+ if err = read("CharTable", func(id uint64, b []byte) error {
+ var c StatisticsCharacter
+ if e := pvpScalars(b, map[int]*uint64{9: &c.Grade, 20: &c.UniqueID}); e != nil {
+ return e
+ }
+ d.Characters[id] = c
+ uniqueGrade[c.UniqueID] = c.Grade
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if err = read("CostumeTable", func(id uint64, b []byte) error {
+ var unique uint64
+ if e := pvpScalars(b, map[int]*uint64{27: &unique}); e != nil {
+ return e
+ }
+ d.CostumeGrade[id] = uniqueGrade[unique]
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if err = read("EquipmentTable", func(id uint64, b []byte) error {
+ var v StatisticsEquipment
+ if e := pvpScalars(b, map[int]*uint64{3: &v.Grade, 16: &v.CharacterUniqueID, 20: &v.Slot, 22: &v.UniqueID}); e != nil {
+ return e
+ }
+ d.Equipment[id] = v
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ castle, err := LoadCastleRewardDesign(root, version)
+ if err != nil {
+ return nil, err
+ }
+ d.CastleStages[7] = map[uint64]uint64{}
+ for id, f := range castle.Floors {
+ for _, battle := range f.Monsters {
+ d.CastleStages[7][battle] = id
+ }
+ }
+ for _, tower := range castle.Towers {
+ if d.CastleStages[tower.Mode] == nil {
+ d.CastleStages[tower.Mode] = map[uint64]uint64{}
+ }
+ d.CastleStages[tower.Mode][tower.Deck] = tower.ID
+ }
+ d.PVPRankGroups = map[uint64]uint64{}
+ if err = read("PvpRankTable", func(id uint64, b []byte) error {
+ var group uint64
+ if e := pvpScalars(b, map[int]*uint64{14: &group}); e != nil {
+ return e
+ }
+ d.PVPRankGroups[id] = group
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if err = read("PvpDefaultTable", func(id uint64, b []byte) error { return pvpScalars(b, map[int]*uint64{22: &d.PVPMinimumGroup}) }); err != nil {
+ return nil, err
+ }
+ d.GachaGroups = map[uint64]uint64{}
+ if err = read("GachaGroupTable", func(group uint64, b []byte) error {
+ for _, field := range []int{24, 33} {
+ ids, e := packedInts(b, field)
+ if e != nil {
+ return e
+ }
+ for _, id := range ids {
+ if id == 0 {
+ continue
+ }
+ if old := d.GachaGroups[id]; old != 0 && old != group {
+ return fmt.Errorf("gacha %d has ambiguous history groups", id)
+ }
+ d.GachaGroups[id] = group
+ }
+ }
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ return d, nil
+}
diff --git a/go/internal/server/design/gamedata/community_rewards.go b/go/internal/server/design/gamedata/community_rewards.go
new file mode 100644
index 0000000..37acc5b
--- /dev/null
+++ b/go/internal/server/design/gamedata/community_rewards.go
@@ -0,0 +1,33 @@
+package gamedata
+
+import "fmt"
+
+type CommunityRewards struct {
+ Community, Survey []Reward
+}
+
+func LoadCommunityRewards(root, version string) (*CommunityRewards, error) {
+ db, closeDB, err := openStatDatabase(root, version)
+ if err != nil {
+ return nil, err
+ }
+ defer closeDB()
+ var raw []byte
+ if err := db.QueryRow("SELECT ProtoBuf FROM CommunityWebLinkTable WHERE id=0").Scan(&raw); err != nil {
+ return nil, err
+ }
+ d := &CommunityRewards{}
+ for _, r := range []struct {
+ count, id, typ int
+ out *[]Reward
+ }{{1, 2, 3, &d.Community}, {65, 66, 67, &d.Survey}} {
+ rewards, err := monsterHuntRewardArrays(raw, r.typ, r.id, r.count)
+ if err != nil || len(rewards) == 0 {
+ return nil, fmt.Errorf("gamedata: invalid community reward arrays: %w", err)
+ }
+ for _, reward := range rewards {
+ *r.out = append(*r.out, Reward(reward))
+ }
+ }
+ return d, nil
+}
diff --git a/go/internal/server/design/gamedata/equipment_craft.go b/go/internal/server/design/gamedata/equipment_craft.go
index 1a8f52b..d94837a 100644
--- a/go/internal/server/design/gamedata/equipment_craft.go
+++ b/go/internal/server/design/gamedata/equipment_craft.go
@@ -1,6 +1,7 @@
package gamedata
import (
+ "bd2server/internal/common/util"
"database/sql"
"fmt"
"math"
@@ -55,7 +56,7 @@ func loadEquipmentCraftDesign(db *sql.DB) (*EquipmentCraftDesign, error) {
design := &EquipmentCraftDesign{
Recipes: make(map[uint64]EquipmentCraftRecipe), Equipment: make(map[uint64]EquipmentDesign),
CharTalent: make(map[uint64]equipmentMakingTalent), Skills: make(map[[2]uint64]equipmentMakingTalentSkill),
- TalentNeed: make(map[[2]uint64]uint64), draw: cryptoDraw,
+ TalentNeed: make(map[[2]uint64]uint64), draw: util.RandomUint64N,
}
rows, err := db.Query("SELECT id,ProtoBuf FROM EquipmentMakingTable ORDER BY id")
if err != nil {
@@ -281,7 +282,7 @@ func (d *EquipmentCraftDesign) Generate(recipeID uint64) (GeneratedEquipment, er
}
draw := d.draw
if draw == nil {
- draw = cryptoDraw
+ draw = util.RandomUint64N
}
id, err := rollEquipmentChoiceWith(recipe.Results, draw)
if err != nil {
diff --git a/go/internal/server/design/gamedata/equipment_gacha.go b/go/internal/server/design/gamedata/equipment_gacha.go
index 9d13083..16cc933 100644
--- a/go/internal/server/design/gamedata/equipment_gacha.go
+++ b/go/internal/server/design/gamedata/equipment_gacha.go
@@ -1,12 +1,11 @@
package gamedata
import (
- "crypto/rand"
+ "bd2server/internal/common/util"
"database/sql"
"errors"
"fmt"
"math"
- "math/big"
"sort"
)
@@ -469,7 +468,7 @@ func (c *EquipmentGachaCatalog) RollOptions(id uint64) (main, sub []EquipmentOpt
for _, choice := range g.Choices {
options = append(options, WeightedEquipment{ID: choice.ID, Weight: choice.Weight})
}
- picked, e := rollEquipmentChoiceWith(options, cryptoDraw)
+ picked, e := rollEquipmentChoiceWith(options, util.RandomUint64N)
if e != nil {
return nil, e
}
@@ -503,7 +502,7 @@ func (g EquipmentGacha) Roll(previousSR, previousUR uint64, fixed EquipmentFixed
}
out := make([]uint64, g.Count)
for i := range out {
- id, err := rollEquipmentChoiceWith(g.Pool, cryptoDraw)
+ id, err := rollEquipmentChoiceWith(g.Pool, util.RandomUint64N)
if err != nil {
return nil, state, err
}
@@ -511,7 +510,7 @@ func (g EquipmentGacha) Roll(previousSR, previousUR uint64, fixed EquipmentFixed
}
return out, state, nil
}
- return g.rollWith(previousSR, previousUR, fixed, cryptoDraw)
+ return g.rollWith(previousSR, previousUR, fixed, util.RandomUint64N)
}
type EquipmentRoll struct {
@@ -595,10 +594,3 @@ func rollEquipmentChoiceWith(pool []WeightedEquipment, draw func(uint64) (uint64
}
return 0, errors.New("gamedata: equipment selection failed")
}
-func cryptoDraw(limit uint64) (uint64, error) {
- n, err := rand.Int(rand.Reader, new(big.Int).SetUint64(limit))
- if err != nil {
- return 0, err
- }
- return n.Uint64(), nil
-}
diff --git a/go/internal/server/design/gamedata/equipment_option_reroll.go b/go/internal/server/design/gamedata/equipment_option_reroll.go
index 3a2810e..20bf5b7 100644
--- a/go/internal/server/design/gamedata/equipment_option_reroll.go
+++ b/go/internal/server/design/gamedata/equipment_option_reroll.go
@@ -1,6 +1,7 @@
package gamedata
import (
+ "bd2server/internal/common/util"
"database/sql"
"fmt"
"math"
@@ -68,7 +69,7 @@ func loadEquipmentOptionRerollDesign(db *sql.DB) (*EquipmentOptionRerollDesign,
Equipment: make(map[uint64]EquipmentOptionRerollItem),
Costs: make(map[uint64]EquipmentOptionRerollCost),
Groups: make(map[uint64]OptionGroup),
- draw: cryptoDraw,
+ draw: util.RandomUint64N,
}
referencedGroups := make(map[uint64]bool)
rows, err := db.Query("SELECT id,ProtoBuf FROM EquipmentTable")
@@ -330,7 +331,7 @@ func (d *EquipmentOptionRerollDesign) rollGroup(groupID uint64) (EquipmentOption
}
draw := d.draw
if draw == nil {
- draw = cryptoDraw
+ draw = util.RandomUint64N
}
id, err := rollEquipmentChoiceWith(pool, draw)
if err != nil {
diff --git a/go/internal/server/design/gamedata/event_ap.go b/go/internal/server/design/gamedata/event_ap.go
index 4c55599..91ddce4 100644
--- a/go/internal/server/design/gamedata/event_ap.go
+++ b/go/internal/server/design/gamedata/event_ap.go
@@ -15,7 +15,7 @@ func LoadEventAPDesign(root, version string) (map[uint64]uint64, HuntingAPDesign
return nil, d, e
}
caps := map[uint64]uint64{}
- for typ, field := range map[uint64]int{30: 43, 32: 113} {
+ for typ, field := range map[uint64]int{30: 43, 32: 113, 35: 102} {
n, e := optionalScalar(raw, field)
if e != nil {
return nil, d, e
diff --git a/go/internal/server/design/gamedata/event_battle.go b/go/internal/server/design/gamedata/event_battle.go
new file mode 100644
index 0000000..e2ea9d3
--- /dev/null
+++ b/go/internal/server/design/gamedata/event_battle.go
@@ -0,0 +1,102 @@
+package gamedata
+
+import (
+ "encoding/binary"
+ "fmt"
+ "math"
+
+ "bd2server/internal/server/protocol/wire"
+)
+
+type EventBattleRule struct {
+ Group, Stage, Deck, APCost uint64
+ Quick bool
+ Rewards []BattleReward
+}
+
+func (c *EventPlayCatalog) EventBattle(group, stage, deck uint64) (EventBattleRule, error) {
+ for _, raw := range c.Rows("PackEventBattleTable", 4, group) {
+ id, err := optionalScalar(raw, 5)
+ if err != nil {
+ return EventBattleRule{}, err
+ }
+ if id != stage {
+ continue
+ }
+ actualDeck, err := optionalScalar(raw, 1)
+ if err != nil {
+ return EventBattleRule{}, err
+ }
+ if deck != 0 && actualDeck != deck {
+ return EventBattleRule{}, fmt.Errorf("gamedata: event battle deck mismatch")
+ }
+ ap, err := optionalScalar(raw, 3)
+ if err != nil {
+ return EventBattleRule{}, err
+ }
+ quick, err := optionalScalar(raw, 7)
+ if err != nil {
+ return EventBattleRule{}, err
+ }
+ rewards, err := eventGameRewards(raw, 9, 10, 8)
+ if err != nil {
+ return EventBattleRule{}, err
+ }
+ return EventBattleRule{Group: group, Stage: stage, Deck: actualDeck, APCost: ap, Quick: quick == 1, Rewards: rewards}, nil
+ }
+ return EventBattleRule{}, fmt.Errorf("gamedata: event battle unavailable")
+}
+
+func (c *EventPlayCatalog) EventBattleBonus(hub uint64, owned map[uint64]bool, rewards []BattleReward) ([]BattleReward, error) {
+ rates := map[[2]uint64]float32{}
+ for _, raw := range c.Rows("PickUpCostumeEventTable", 3, hub) {
+ costume, err := optionalScalar(raw, 2)
+ if err != nil {
+ return nil, err
+ }
+ if !owned[costume] {
+ continue
+ }
+ ids, err := packedInts(raw, 5)
+ if err != nil {
+ return nil, err
+ }
+ types, err := packedInts(raw, 6)
+ if err != nil {
+ return nil, err
+ }
+ var bonus []float32
+ if err := wire.Walk(raw, func(f wire.Field) error {
+ if f.Number != 1 {
+ return nil
+ }
+ if f.Type != 2 && f.Type != 5 || len(f.Value)%4 != 0 {
+ return fmt.Errorf("gamedata: invalid event bonus")
+ }
+ for at := 0; at < len(f.Value); at += 4 {
+ bonus = append(bonus, math.Float32frombits(binary.LittleEndian.Uint32(f.Value[at:])))
+ }
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if len(ids) != len(types) || len(ids) != len(bonus) {
+ return nil, fmt.Errorf("gamedata: event bonus arrays differ")
+ }
+ for i, rate := range bonus {
+ if math.IsNaN(float64(rate)) || math.IsInf(float64(rate), 0) || rate < 0 {
+ return nil, fmt.Errorf("gamedata: invalid event bonus rate")
+ }
+ rates[[2]uint64{types[i], ids[i]}] += rate
+ }
+ }
+ out := append([]BattleReward(nil), rewards...)
+ for i, r := range out {
+ count := math.Floor(float64(float32(r.Count) * (1 + rates[[2]uint64{r.Type, r.ID}])))
+ if count > math.MaxInt32 || count < 0 {
+ return nil, fmt.Errorf("gamedata: event bonus overflow")
+ }
+ out[i].Count = uint64(count)
+ }
+ return out, nil
+}
diff --git a/go/internal/server/design/gamedata/event_play.go b/go/internal/server/design/gamedata/event_play.go
index 93d257e..ab1766f 100644
--- a/go/internal/server/design/gamedata/event_play.go
+++ b/go/internal/server/design/gamedata/event_play.go
@@ -28,6 +28,7 @@ func LoadEventPlayCatalog(root, version string) (*EventPlayCatalog, error) {
names = append(names, "FieldMiniGameCollectionTable", "FieldMiniGameMapGroupTable", "FieldMiniGameStarterTable", "SichuanDefaultTable", "SichuanBlockDesignTable", "RhythmGameDefaultTable", "RhythmGameCharTable", "HopscotchGalleryTable", "HopscotchRankingTable", "HopscotchAbuseTable")
names = append(names, "PackManDefaultTable", "PackManModeTable", "PackManModeRuleTable", "PackManScoreTable", "PackManMapTable", "PackManObjectTable", "PackManItemTable", "PackManChaserTable", "PackManChaserSpawnTable", "PackManChainTable", "PackManGalleryTable", "PackManGuideTable")
names = append(names, "ActionGameTable", "ActionGameCharTable")
+ names = append(names, "PickUpCostumeEventTable")
names = append(names, "FishingDefaultTable", "FishingMapTable", "FishingMapGroupTable", "FishingBoatTable", "FishingBoatDesignTable", "FishingRodTable", "FishingItemTable", "FishingCharTable", "FishingFishTable", "FishingFishPoolTable", "FishingFishSizePoolTable", "FishingGradePoolTable", "FishingCastingTable", "FishingBuffTable", "FishingBoatBuffTable", "FishingFishSkillTable", "FishingTimeTable")
names = append(names, "FishingBuyItemTable", "FishingSellItemTable", "FishingShopTable", "FishingPricePremiumDefaultTable")
names = append(names, "GameDefaultTable", "FishingInventoryBuyTable")
diff --git a/go/internal/server/design/gamedata/field_objects.go b/go/internal/server/design/gamedata/field_objects.go
index 3d1ec9c..b3de003 100644
--- a/go/internal/server/design/gamedata/field_objects.go
+++ b/go/internal/server/design/gamedata/field_objects.go
@@ -1,6 +1,7 @@
package gamedata
import (
+ "bd2server/internal/common/util"
"database/sql"
"fmt"
)
@@ -155,7 +156,7 @@ func loadFieldObjects(db, common *sql.DB) (FieldObjectDesign, error) {
// DropType 0 makes DropCount weighted selections. DropType 1 checks each
// component's percentage independently; its DropCount may be proto default zero.
func (o FieldRewardObject) Draw() ([]BattleReward, error) {
- return o.draw(cryptoDraw)
+ return o.draw(util.RandomUint64N)
}
// Validate every OPEN branch before the catalog is installed, including zero
diff --git a/go/internal/server/design/gamedata/field_pack.go b/go/internal/server/design/gamedata/field_pack.go
index 8209fb9..0495c4b 100644
--- a/go/internal/server/design/gamedata/field_pack.go
+++ b/go/internal/server/design/gamedata/field_pack.go
@@ -47,7 +47,7 @@ func loadFieldPacks(db *sql.DB) (map[int]FieldPack, error) {
values[field] = v[0]
}
}
- if values[55] != 3 && values[55] != 5 && values[55] != 10 {
+ if values[55] != 3 && values[55] != 4 && values[55] != 5 && values[55] != 7 && values[55] != 10 {
continue
}
if id <= 0 || values[25] != uint64(id) {
diff --git a/go/internal/server/design/gamedata/first_gacha.go b/go/internal/server/design/gamedata/first_gacha.go
index 7862fda..8d69eda 100644
--- a/go/internal/server/design/gamedata/first_gacha.go
+++ b/go/internal/server/design/gamedata/first_gacha.go
@@ -1,6 +1,7 @@
package gamedata
import (
+ "bd2server/internal/common/util"
"database/sql"
"errors"
"fmt"
@@ -299,7 +300,7 @@ func firstGachaRewardCount(g *FirstGachaRewardGroup, visiting map[*FirstGachaRew
return total, nil
}
-func (d *FirstGachaDesign) Roll() ([]FirstGachaReward, error) { return d.roll(cryptoDraw) }
+func (d *FirstGachaDesign) Roll() ([]FirstGachaReward, error) { return d.roll(util.RandomUint64N) }
func (d *FirstGachaDesign) roll(draw func(uint64) (uint64, error)) ([]FirstGachaReward, error) {
if d == nil {
return nil, errors.New("gamedata: missing first gacha")
diff --git a/go/internal/server/design/gamedata/gacha.go b/go/internal/server/design/gamedata/gacha.go
index 1cd174d..8e69533 100644
--- a/go/internal/server/design/gamedata/gacha.go
+++ b/go/internal/server/design/gamedata/gacha.go
@@ -1,14 +1,13 @@
package gamedata
import (
- "crypto/rand"
+ "bd2server/internal/common/util"
"database/sql"
"encoding/binary"
"errors"
"fmt"
"maps"
"math"
- "math/big"
"slices"
"sort"
@@ -410,8 +409,7 @@ func (c *RegularGachaCatalog) SpecialSelectionIDs(gachaID uint64) []uint64 {
}
// FiveStarIDs returns the selectable five-star costumes in one ordinary
-// gacha's authoritative reward pool. Unlike SpecialSelectionIDs it also
-// supports a normal rarity tree, which is used by the newbie guaranteed draw.
+// gacha's authoritative reward pool, including composite reward programs.
func (c *RegularGachaCatalog) FiveStarIDs(gachaID uint64) []uint64 {
gacha, ok := c.Gacha(gachaID)
if !ok {
@@ -433,6 +431,14 @@ func (c *RegularGachaCatalog) FiveStarIDs(gachaID uint64) []uint64 {
}
}
visit(gacha.Pool)
+ var rewardIDs []uint64
+ collectCostumeRewardIDs(gacha.RewardGroup, &rewardIDs)
+ for _, id := range rewardIDs {
+ if c.grades[id] == 5 && !seen[id] {
+ seen[id] = true
+ result = append(result, id)
+ }
+ }
slices.Sort(result)
return result
}
@@ -447,21 +453,9 @@ func (c *RegularGachaCatalog) SpecialSelectionCount(gachaID uint64) uint64 {
func (g RegularGacha) Roll() ([]uint64, error) {
if g.RewardGroup != nil {
- return g.rollRewardGroup(func(limit uint64) (uint64, error) {
- selected, err := rand.Int(rand.Reader, new(big.Int).SetUint64(limit))
- if err != nil {
- return 0, err
- }
- return selected.Uint64(), nil
- })
+ return g.rollRewardGroup(util.RandomUint64N)
}
- return g.rollWith(func(limit uint64) (uint64, error) {
- selected, err := rand.Int(rand.Reader, new(big.Int).SetUint64(limit))
- if err != nil {
- return 0, err
- }
- return selected.Uint64(), nil
- })
+ return g.rollWith(util.RandomUint64N)
}
// RollSpecialSelection executes a composite selection-gacha program while
@@ -470,13 +464,7 @@ func (g RegularGacha) Roll() ([]uint64, error) {
// table IDs: a sequential root first emits the selected rewards and then
// executes the remaining GameData reward branches unchanged.
func (g RegularGacha) RollSpecialSelection(selected []uint64) ([]uint64, error) {
- return g.rollSpecialSelection(selected, func(limit uint64) (uint64, error) {
- value, err := rand.Int(rand.Reader, new(big.Int).SetUint64(limit))
- if err != nil {
- return 0, err
- }
- return value.Uint64(), nil
- })
+ return g.rollSpecialSelection(selected, util.RandomUint64N)
}
func (g RegularGacha) rollSpecialSelection(selected []uint64, draw func(uint64) (uint64, error)) ([]uint64, error) {
@@ -544,13 +532,7 @@ func (g RegularGacha) RollWithCostumeFixed(previous4, previous5 uint64, fixed Ga
}
func (g RegularGacha) RollWithCostumeFixedSelection(previous4, previous5 uint64, fixed GachaFixedDesign, normalSelectedFive, pitySelectedFive []uint64) ([]uint64, GachaFixedRoll, error) {
- return g.rollWithCostumeFixed(previous4, previous5, fixed, normalSelectedFive, pitySelectedFive, func(limit uint64) (uint64, error) {
- selected, err := rand.Int(rand.Reader, new(big.Int).SetUint64(limit))
- if err != nil {
- return 0, err
- }
- return selected.Uint64(), nil
- })
+ return g.rollWithCostumeFixed(previous4, previous5, fixed, normalSelectedFive, pitySelectedFive, util.RandomUint64N)
}
func (g RegularGacha) rollWithCostumeFixed(previous4, previous5 uint64, fixed GachaFixedDesign, normalSelectedFive, pitySelectedFive []uint64, draw func(uint64) (uint64, error)) ([]uint64, GachaFixedRoll, error) {
@@ -1762,13 +1744,7 @@ func fixed64Double(proto []byte, number int) (float64, bool, error) {
}
func (d *InfiniteGachaDesign) Roll() ([]uint64, error) {
- return d.rollWith(func(limit uint64) (uint64, error) {
- selected, err := rand.Int(rand.Reader, new(big.Int).SetUint64(limit))
- if err != nil {
- return 0, err
- }
- return selected.Uint64(), nil
- })
+ return d.rollWith(util.RandomUint64N)
}
func (d *InfiniteGachaDesign) rollWith(draw func(uint64) (uint64, error)) ([]uint64, error) {
diff --git a/go/internal/server/design/gamedata/ib.go b/go/internal/server/design/gamedata/ib.go
new file mode 100644
index 0000000..0623292
--- /dev/null
+++ b/go/internal/server/design/gamedata/ib.go
@@ -0,0 +1,189 @@
+package gamedata
+
+import (
+ "encoding/binary"
+ "fmt"
+ "slices"
+
+ "bd2server/internal/server/protocol/wire"
+)
+
+type IBPoint struct{ X, Y int }
+type IBItem struct {
+ ID, Type, Grade, Price, SellType, TypeID, CostumeID uint64
+ Shape []IBPoint
+}
+type IBPlacement struct{ ItemID, Position, Rotation uint64 }
+type IBStage struct {
+ ID, EnemyDeck, Credit uint64
+ Ratios [7]uint64
+ Slots [4]uint64
+}
+type IBDungeon struct {
+ ID, Life, Unlock uint64
+ Reward Reward
+ Stages []IBStage
+}
+type IBDesign struct {
+ StartDeck, RetryCredit, RefreshPriceUp, DiscountRate uint64
+ Seasons map[uint64][]uint64
+ Dungeons map[uint64]IBDungeon
+ Items map[uint64]IBItem
+ Decks map[uint64][]IBPlacement
+ UpgradeCosts map[[3]uint64]uint64
+ Sockets map[[2]uint64][]IBPoint
+}
+
+func ibNumbers(raw []byte, packed ...int) (map[int][]uint64, error) {
+ out := map[int][]uint64{}
+ err := wire.Walk(raw, func(f wire.Field) error {
+ if f.Type == 0 {
+ v, n := binary.Uvarint(f.Value)
+ if n <= 0 {
+ return wire.ErrMalformed
+ }
+ out[f.Number] = append(out[f.Number], v)
+ } else if f.Type == 2 && slices.Contains(packed, f.Number) {
+ for data := f.Value; len(data) > 0; {
+ v, n := binary.Uvarint(data)
+ if n <= 0 {
+ return wire.ErrMalformed
+ }
+ out[f.Number] = append(out[f.Number], v)
+ data = data[n:]
+ }
+ }
+ return nil
+ })
+ return out, err
+}
+
+func LoadIBDesign(root, version string) (*IBDesign, error) {
+ db, done, err := openStatDatabase(root, version)
+ if err != nil {
+ return nil, err
+ }
+ defer done()
+ d := &IBDesign{Seasons: map[uint64][]uint64{}, Dungeons: map[uint64]IBDungeon{}, Items: map[uint64]IBItem{}, Decks: map[uint64][]IBPlacement{}, UpgradeCosts: map[[3]uint64]uint64{}, Sockets: map[[2]uint64][]IBPoint{}}
+ stages := map[uint64][]IBStage{}
+ for _, spec := range []struct {
+ name string
+ packed []int
+ }{
+ {"IBDefaultTable", nil}, {"IBSeasonTable", []int{1}}, {"IBItemTable", []int{13, 14}}, {"IBDeckTable", []int{2, 3, 4}}, {"IBStageTable", nil}, {"IBDungeonTable", nil}, {"IBUnitItemTable", []int{21, 22}}, {"IBEquipItemTable", nil},
+ } {
+ rows, e := db.Query("SELECT ProtoBuf FROM " + spec.name)
+ if e != nil {
+ return nil, e
+ }
+ for rows.Next() {
+ var raw []byte
+ if e = rows.Scan(&raw); e != nil {
+ break
+ }
+ var f map[int][]uint64
+ f, e = ibNumbers(raw, spec.packed...)
+ if e != nil {
+ break
+ }
+ v := func(n int) uint64 {
+ if len(f[n]) > 0 {
+ return f[n][0]
+ }
+ return 0
+ }
+ switch spec.name {
+ case "IBDefaultTable":
+ d.StartDeck = v(22)
+ d.RetryCredit = v(18)
+ d.RefreshPriceUp = v(20)
+ d.DiscountRate = v(19)
+ case "IBSeasonTable":
+ d.Seasons[v(2)] = f[1]
+ case "IBItemTable":
+ i := IBItem{ID: v(3), Type: v(11), Grade: v(5), Price: v(8), SellType: v(12), TypeID: v(15), CostumeID: v(1)}
+ if len(f[13]) != len(f[14]) {
+ e = fmt.Errorf("ib: item shape mismatch %d", i.ID)
+ break
+ }
+ for n, x := range f[13] {
+ i.Shape = append(i.Shape, IBPoint{int(int32(x)), int(int32(f[14][n]))})
+ }
+ d.Items[i.ID] = i
+ case "IBDeckTable":
+ if len(f[2]) != len(f[4]) || len(f[3]) != len(f[4]) {
+ e = fmt.Errorf("ib: malformed deck %d", v(1))
+ break
+ }
+ for n, id := range f[4] {
+ d.Decks[v(1)] = append(d.Decks[v(1)], IBPlacement{id, f[2][n], f[3][n]})
+ }
+ case "IBStageTable":
+ stages[v(5)] = append(stages[v(5)], IBStage{ID: v(8), EnemyDeck: v(2), Credit: v(4), Ratios: [7]uint64{v(11), v(12), v(1), v(7), v(9), v(10), v(17)}, Slots: [4]uint64{v(13), v(14), v(15), v(16)}})
+ case "IBDungeonTable":
+ d.Dungeons[v(6)] = IBDungeon{ID: v(6), Life: v(4), Unlock: v(9), Reward: Reward{v(3), v(2), v(1)}, Stages: []IBStage{{ID: v(8)}}}
+ case "IBUnitItemTable":
+ d.UpgradeCosts[[3]uint64{1, v(5), v(7)}] = v(23)
+ if len(f[21]) != len(f[22]) {
+ e = fmt.Errorf("ib: socket shape mismatch")
+ break
+ }
+ for n, x := range f[21] {
+ d.Sockets[[2]uint64{v(5), v(7)}] = append(d.Sockets[[2]uint64{v(5), v(7)}], IBPoint{int(int32(x)), int(int32(f[22][n]))})
+ }
+ case "IBEquipItemTable":
+ d.UpgradeCosts[[3]uint64{2, v(2), v(3)}] = v(7)
+ }
+ if e != nil {
+ break
+ }
+ }
+ if e == nil {
+ e = rows.Err()
+ }
+ _ = rows.Close()
+ if e != nil {
+ return nil, e
+ }
+ }
+ for id, dungeon := range d.Dungeons {
+ group := dungeon.Stages[0].ID
+ dungeon.Stages = stages[group]
+ slices.SortFunc(dungeon.Stages, func(a, b IBStage) int {
+ if a.ID < b.ID {
+ return -1
+ }
+ if a.ID > b.ID {
+ return 1
+ }
+ return 0
+ })
+ if dungeon.Life == 0 || len(dungeon.Stages) == 0 || dungeon.Reward.Type == 0 || dungeon.Reward.Count == 0 {
+ return nil, fmt.Errorf("ib: invalid dungeon %d", id)
+ }
+ for _, s := range dungeon.Stages {
+ if len(d.Decks[s.EnemyDeck]) == 0 {
+ return nil, fmt.Errorf("ib: missing enemy deck %d", s.EnemyDeck)
+ }
+ }
+ d.Dungeons[id] = dungeon
+ }
+ if len(d.Decks[d.StartDeck]) == 0 || len(d.Seasons) == 0 {
+ return nil, fmt.Errorf("ib: invalid defaults")
+ }
+ for _, ids := range d.Seasons {
+ for _, id := range ids {
+ if _, ok := d.Dungeons[id]; !ok {
+ return nil, fmt.Errorf("ib: missing season dungeon %d", id)
+ }
+ }
+ }
+ for _, deck := range d.Decks {
+ for _, p := range deck {
+ if _, ok := d.Items[p.ItemID]; !ok {
+ return nil, fmt.Errorf("ib: missing item %d", p.ItemID)
+ }
+ }
+ }
+ return d, nil
+}
diff --git a/go/internal/server/design/gamedata/life.go b/go/internal/server/design/gamedata/life.go
new file mode 100644
index 0000000..97ae3cd
--- /dev/null
+++ b/go/internal/server/design/gamedata/life.go
@@ -0,0 +1,144 @@
+package gamedata
+
+import (
+ "fmt"
+ "slices"
+ "sort"
+
+ "bd2server/internal/server/protocol/wire"
+)
+
+// LifeCatalog is loaded once at assembly and shared read-only by player actors.
+type LifeCatalog struct {
+ Tables map[string]map[[3]uint64][]byte
+ WorldDefaults map[uint64][][]byte
+ Gathering map[uint64]map[uint64][][]byte
+ ItemsByUnique map[uint64][][]byte
+ ToolGroups map[uint64][]uint64
+ HelperUniques map[uint64][]uint64
+ CollectionsByItem map[[2]uint64][]uint64
+ MaxChunks uint64
+}
+
+var lifeKeys = map[string][]int{
+ "LifeDefaultTable": {21}, "LifeWorldTable": {4}, "LifeDefaultObjectGroupTable": {3},
+ "LifeObjectGroupTable": {5}, "LifeBuildingObjectTable": {4}, "LifeCraftingObjectTable": {1},
+ "LifeDecoObjectTable": {1}, "LifeChunkExpandTable": {4}, "LifeCharGrowthTable": {2, 3},
+ "LifeGatheringObjectTable": {4, 6, 10}, "LifeItemTable": {5}, "LifeToolTable": {5, 7},
+ "LifeCookTable": {1}, "LifeCropSeedTable": {2}, "LifeCropGradeTable": {2},
+ "LifeBuyItemTable": {1, 2}, "LifeSellItemTable": {1, 2}, "LifeBuffTable": {8},
+ "LifeHelperSpeciesTable": {9}, "LifeCollectionTable": {4},
+}
+
+func LoadLifeCatalog(root, version string) (*LifeCatalog, error) {
+ db, done, err := openStatDatabase(root, version)
+ if err != nil {
+ return nil, err
+ }
+ defer done()
+ tables := map[string][][]byte{}
+ for table := range lifeKeys {
+ if err := readCashMetadata(db, table, func(raw []byte) error { tables[table] = append(tables[table], append([]byte(nil), raw...)); return nil }); err != nil {
+ return nil, err
+ }
+ }
+ return NewLifeCatalog(tables)
+}
+
+func NewLifeCatalog(tables map[string][][]byte) (*LifeCatalog, error) {
+ c := &LifeCatalog{Tables: map[string]map[[3]uint64][]byte{}, WorldDefaults: map[uint64][][]byte{}, Gathering: map[uint64]map[uint64][][]byte{}, ItemsByUnique: map[uint64][][]byte{}, ToolGroups: map[uint64][]uint64{}, HelperUniques: map[uint64][]uint64{}, CollectionsByItem: map[[2]uint64][]uint64{}}
+ for table, keys := range lifeKeys {
+ c.Tables[table] = map[[3]uint64][]byte{}
+ for _, raw := range tables[table] {
+ if err := wire.Walk(raw, func(wire.Field) error { return nil }); err != nil {
+ return nil, err
+ }
+ var key [3]uint64
+ for i, field := range keys {
+ key[i], _, _ = wire.Varint(raw, field)
+ }
+ if _, exists := c.Tables[table][key]; exists {
+ return nil, fmt.Errorf("life: duplicate %s key %v", table, key)
+ }
+ c.Tables[table][key] = append([]byte(nil), raw...)
+ n := func(f int) uint64 { v, _, _ := wire.Varint(raw, f); return v }
+ switch table {
+ case "LifeDefaultObjectGroupTable":
+ c.WorldDefaults[n(8)] = append(c.WorldDefaults[n(8)], raw)
+ case "LifeGatheringObjectTable":
+ if c.Gathering[n(4)] == nil {
+ c.Gathering[n(4)] = map[uint64][][]byte{}
+ }
+ c.Gathering[n(4)][n(6)] = append(c.Gathering[n(4)][n(6)], raw)
+ case "LifeItemTable":
+ c.ItemsByUnique[n(10)] = append(c.ItemsByUnique[n(10)], raw)
+ case "LifeToolTable":
+ c.ToolGroups[n(5)] = append(c.ToolGroups[n(5)], n(7))
+ case "LifeCollectionTable":
+ c.CollectionsByItem[[2]uint64{n(2), n(1)}] = append(c.CollectionsByItem[[2]uint64{n(2), n(1)}], n(4))
+ case "LifeChunkExpandTable":
+ c.MaxChunks = max(c.MaxChunks, n(4))
+ }
+ }
+ }
+ for _, rows := range c.WorldDefaults {
+ sort.Slice(rows, func(i, j int) bool {
+ a, _, _ := wire.Varint(rows[i], 3)
+ b, _, _ := wire.Varint(rows[j], 3)
+ return a < b
+ })
+ }
+ for _, variants := range c.Gathering {
+ for _, rows := range variants {
+ sort.Slice(rows, func(i, j int) bool {
+ a, _, _ := wire.Varint(rows[i], 10)
+ b, _, _ := wire.Varint(rows[j], 10)
+ return a < b
+ })
+ }
+ }
+ for _, ids := range c.ToolGroups {
+ slices.Sort(ids)
+ }
+ for _, rows := range c.ItemsByUnique {
+ sort.Slice(rows, func(i, j int) bool {
+ a, _, _ := wire.Varint(rows[i], 3)
+ b, _, _ := wire.Varint(rows[j], 3)
+ return a < b
+ })
+ }
+ seen := map[uint64]map[uint64]bool{}
+ for _, variants := range c.Gathering {
+ for _, rows := range variants {
+ for _, r := range rows {
+ f, _, _ := wire.Varint(r, 2)
+ if seen[f] == nil {
+ seen[f] = map[uint64]bool{}
+ }
+ items, err := packedInts(r, 9)
+ if err != nil {
+ return nil, err
+ }
+ for _, u := range items {
+ seen[f][u] = true
+ }
+ }
+ }
+ }
+ for f, items := range seen {
+ for u := range items {
+ c.HelperUniques[f] = append(c.HelperUniques[f], u)
+ }
+ slices.Sort(c.HelperUniques[f])
+ }
+ if c.Row("LifeDefaultTable", 0) == nil || len(c.Tables["LifeWorldTable"]) == 0 {
+ return nil, fmt.Errorf("life: missing defaults or worlds")
+ }
+ return c, nil
+}
+
+func (c *LifeCatalog) Row(table string, key ...uint64) []byte {
+ var k [3]uint64
+ copy(k[:], key)
+ return c.Tables[table][k]
+}
diff --git a/go/internal/server/design/gamedata/quest_titles.go b/go/internal/server/design/gamedata/quest_titles.go
new file mode 100644
index 0000000..309175d
--- /dev/null
+++ b/go/internal/server/design/gamedata/quest_titles.go
@@ -0,0 +1,44 @@
+package gamedata
+
+import (
+ "fmt"
+ "math"
+)
+
+type QuestTitle struct {
+ ID, FirstQuest, LastQuest int
+}
+
+func loadQuestTitles(root, version string, pack int) ([]QuestTitle, error) {
+ db, release, err := openPackDatabase(root, version, pack)
+ if err != nil {
+ return nil, err
+ }
+ defer release()
+ rows, err := db.Query("SELECT id,ProtoBuf FROM QuestTitleTable ORDER BY id")
+ if err != nil {
+ return nil, fmt.Errorf("gamedata: quest titles pack%d: %w", pack, err)
+ }
+ defer func() { _ = rows.Close() }()
+ var titles []QuestTitle
+ for rows.Next() {
+ var id int
+ var raw []byte
+ if err := rows.Scan(&id, &raw); err != nil {
+ return nil, err
+ }
+ var title QuestTitle
+ for field, target := range map[int]*int{1: &title.LastQuest, 2: &title.FirstQuest, 3: &title.ID} {
+ values, err := packedInts(raw, field)
+ if err != nil || len(values) != 1 || values[0] > math.MaxInt32 {
+ return nil, fmt.Errorf("gamedata: invalid quest title pack%d id%d field%d", pack, id, field)
+ }
+ *target = int(values[0])
+ }
+ if title.ID != id || id <= 0 || title.FirstQuest <= 0 || title.LastQuest < title.FirstQuest {
+ return nil, fmt.Errorf("gamedata: invalid quest title pack%d id%d", pack, id)
+ }
+ titles = append(titles, title)
+ }
+ return titles, rows.Err()
+}
diff --git a/go/internal/server/design/gamedata/resource_items.go b/go/internal/server/design/gamedata/resource_items.go
new file mode 100644
index 0000000..5b906bb
--- /dev/null
+++ b/go/internal/server/design/gamedata/resource_items.go
@@ -0,0 +1,89 @@
+package gamedata
+
+import (
+ "fmt"
+ "math"
+)
+
+type ResourceItemDesign struct {
+ Selections map[uint64]map[uint64]BattleReward
+}
+
+func LoadResourceItemDesign(root, version string) (*ResourceItemDesign, error) {
+ db, done, err := openStatDatabase(root, version)
+ if err != nil {
+ return nil, err
+ }
+ defer done()
+ groups := map[uint64]map[uint64]BattleReward{}
+ if err := readCashMetadata(db, "RewardGroupTable", func(raw []byte) error {
+ id, err := optionalScalar(raw, 3)
+ if err != nil {
+ return err
+ }
+ rewards, err := eventGameRewards(raw, 6, 5, 4)
+ if err != nil {
+ return err
+ }
+ options := map[uint64]BattleReward{}
+ for _, r := range rewards {
+ if r.Type == 11 && r.ID != 0 && r.Count > 0 {
+ options[r.ID] = r
+ }
+ }
+ groups[id] = options
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ selections := map[uint64]map[uint64]BattleReward{}
+ if err := readCashMetadata(db, "CostumeSelectTable", func(raw []byte) error {
+ id, err := optionalScalar(raw, 2)
+ if err != nil {
+ return err
+ }
+ group, err := optionalScalar(raw, 1)
+ if err != nil {
+ return err
+ }
+ selections[id] = groups[group]
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ d := &ResourceItemDesign{Selections: map[uint64]map[uint64]BattleReward{}}
+ if err := readCashMetadata(db, "ResourceTable", func(raw []byte) error {
+ kind, err := optionalScalar(raw, 13)
+ if err != nil || kind != 6 {
+ return err
+ }
+ id, err := optionalScalar(raw, 4)
+ if err != nil {
+ return err
+ }
+ selection, err := optionalScalar(raw, 9)
+ if err != nil {
+ return err
+ }
+ if id == 0 || len(selections[selection]) == 0 {
+ return fmt.Errorf("gamedata: resource %d has no costume choices", id)
+ }
+ d.Selections[id] = selections[selection]
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ return d, nil
+}
+
+func (d *ResourceItemDesign) Select(resource, selection, count uint64) ([]BattleReward, error) {
+ if d == nil || count == 0 || count > math.MaxInt32 {
+ return nil, fmt.Errorf("gamedata: invalid resource item use")
+ }
+ r, ok := d.Selections[resource][selection]
+ if !ok || r.Type != 11 || r.ID != selection || r.Count == 0 || r.Count > math.MaxInt32/count {
+ return nil, fmt.Errorf("gamedata: unavailable costume choice")
+ }
+ r.Count *= count
+ return []BattleReward{r}, nil
+}
diff --git a/go/internal/server/design/gamedata/reward_graph.go b/go/internal/server/design/gamedata/reward_graph.go
index 3449306..d6c0d05 100644
--- a/go/internal/server/design/gamedata/reward_graph.go
+++ b/go/internal/server/design/gamedata/reward_graph.go
@@ -1,11 +1,10 @@
package gamedata
import (
- "crypto/rand"
+ "bd2server/internal/common/util"
"database/sql"
"fmt"
"math"
- "math/big"
"sort"
"sync"
)
@@ -36,11 +35,7 @@ func loadRewardGraph(db *sql.DB) (*RewardGraph, error) {
if n == 0 {
return 0, fmt.Errorf("gamedata: empty reward pool")
}
- v, e := rand.Int(rand.Reader, new(big.Int).SetUint64(n))
- if e != nil {
- return 0, e
- }
- return v.Uint64(), nil
+ return util.RandomUint64N(n)
}
rows, e := db.Query("SELECT id,ProtoBuf FROM RandomBoxTable")
if e != nil {
diff --git a/go/internal/server/design/gamedata/reward_skin.go b/go/internal/server/design/gamedata/reward_skin.go
index f86c0dc..cbdec7a 100644
--- a/go/internal/server/design/gamedata/reward_skin.go
+++ b/go/internal/server/design/gamedata/reward_skin.go
@@ -11,8 +11,9 @@ type PrestigeSkinSelling struct {
}
type PrestigeSkinCatalog struct {
- Skins map[uint64]uint64
- Selling []PrestigeSkinSelling
+ Skins map[uint64]uint64
+ Illustrations map[uint64]uint64
+ Selling []PrestigeSkinSelling
}
// LoadPrestigeSkinCatalog loads the skin ownership mapping and the separate
@@ -29,7 +30,7 @@ func LoadPrestigeSkinCatalog(root, version string) (*PrestigeSkinCatalog, error)
return nil, e
}
defer func() { _ = rows.Close() }()
- catalog := &PrestigeSkinCatalog{Skins: map[uint64]uint64{}}
+ catalog := &PrestigeSkinCatalog{Skins: map[uint64]uint64{}, Illustrations: map[uint64]uint64{}}
for rows.Next() {
var id uint64
var raw []byte
@@ -44,11 +45,38 @@ func LoadPrestigeSkinCatalog(root, version string) (*PrestigeSkinCatalog, error)
return nil, fmt.Errorf("gamedata: invalid prestige skin %d", id)
}
catalog.Skins[id] = costume
+ illustration, err := optionalScalar(raw, 7)
+ if err != nil {
+ return nil, err
+ }
+ if illustration != 0 {
+ catalog.Illustrations[id] = illustration
+ }
}
if e := rows.Err(); e != nil {
return nil, e
}
_ = rows.Close()
+ matched := 0
+ if err := readCashMetadata(db, "LobbySettingItemTable", func(raw []byte) error {
+ id, err := optionalScalar(raw, 3)
+ if err != nil {
+ return err
+ }
+ skin, err := optionalScalar(raw, 9)
+ if err != nil {
+ return err
+ }
+ if skin != 0 && catalog.Illustrations[skin] == id {
+ matched++
+ }
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if matched != len(catalog.Illustrations) {
+ return nil, fmt.Errorf("gamedata: prestige illustration ownership mapping is incomplete")
+ }
rows, e = db.Query("SELECT ProtoBuf FROM SkinSellingTable ORDER BY groupId,id")
if e != nil {
return nil, e
diff --git a/go/internal/server/design/gamedata/roguelike.go b/go/internal/server/design/gamedata/roguelike.go
new file mode 100644
index 0000000..a470f47
--- /dev/null
+++ b/go/internal/server/design/gamedata/roguelike.go
@@ -0,0 +1,265 @@
+package gamedata
+
+import (
+ "bd2server/internal/server/protocol/wire"
+ "encoding/binary"
+ "fmt"
+ "math"
+ "slices"
+)
+
+type RogueRule struct {
+ Values map[int][]uint64
+ Decimals map[int]float64
+}
+
+func (r RogueRule) V(f int) uint64 {
+ if a := r.Values[f]; len(a) > 0 {
+ return a[0]
+ }
+ return 0
+}
+func (r RogueRule) A(f int) []uint64 { return r.Values[f] }
+func (r RogueRule) D(f int) float64 { return r.Decimals[f] }
+
+type RogueTable struct {
+ Rows map[[2]uint64]RogueRule
+ Groups map[uint64][]uint64
+}
+
+func (t RogueTable) Row(g, id uint64) RogueRule { return t.Rows[[2]uint64{g, id}] }
+
+type RogueEnemy struct{ ID, Level, Position uint64 }
+type RogueCostume struct {
+ ID, Character, Unique, MaxLevel, MaxBurst uint64
+ Health uint64
+ RequiresOwnership bool
+}
+type RogueLikeDesign struct {
+ PackOpen ContentOpenRule
+ Open ContentOpenRule
+ Default RogueRule
+ Buffs RogueTable
+ Floors, Rooms, Levels, Growth, Relics, RelicChoices, Mix, Events, EventChoices, Effects, Scores, Shops, Rewards RogueTable
+ Pack uint64
+ Enemies map[uint64][]RogueEnemy
+ Costumes map[uint64]RogueCostume
+ CostumeIDs []uint64
+}
+
+func LoadRogueLikeDesign(root, version string) (*RogueLikeDesign, error) {
+ db, done, e := openStatDatabase(root, version)
+ if e != nil {
+ return nil, e
+ }
+ defer done()
+ d := &RogueLikeDesign{Costumes: map[uint64]RogueCostume{}}
+ var access []byte
+ if e = db.QueryRow("SELECT ProtoBuf FROM ContentOpenTable WHERE groupId=18 AND id=1").Scan(&access); e != nil {
+ return nil, e
+ }
+ d.Open.SquadLevel, e = optionalScalar(access, 5)
+ if e != nil {
+ return nil, e
+ }
+ d.Open.TicketID, e = optionalScalar(access, 6)
+ if e != nil {
+ return nil, e
+ }
+
+ for _, spec := range []struct {
+ name string
+ g, id int
+ table *RogueTable
+ packed []int
+ }{
+ {"RLDefaultTable", 0, 26, nil, []int{2}},
+ {"RLBuffTable", 0, 8, &d.Buffs, []int{5}},
+ {"RLFloorTable", 7, 8, &d.Floors, []int{11, 12}}, {"RLRoomTable", 6, 7, &d.Rooms, []int{8}},
+ {"RLLevelTable", 0, 6, &d.Levels, []int{1, 8, 9, 10}}, {"RLGrowthTable", 1, 7, &d.Growth, nil},
+ {"RLRelicTable", 0, 2, &d.Relics, []int{3}}, {"RLRelicChoiceTable", 0, 1, &d.RelicChoices, []int{2}},
+ {"RLRelicMixTable", 0, 1, &d.Mix, nil}, {"RLEventTable", 13, 14, &d.Events, []int{1, 2, 3, 4, 5, 6, 7, 10}},
+ {"RLEventChoiceTable", 0, 2, &d.EventChoices, []int{1}}, {"RLEventEffectTypeTable", 0, 5, &d.Effects, nil},
+ {"RLScoreTable", 0, 1, &d.Scores, nil}, {"RLShopTable", 0, 2, &d.Shops, []int{1}}, {"RLRewardTable", 0, 1, &d.Rewards, []int{2, 3, 4}},
+ } {
+ table := RogueTable{Rows: map[[2]uint64]RogueRule{}, Groups: map[uint64][]uint64{}}
+ rows, e := db.Query("SELECT ProtoBuf FROM " + spec.name)
+ if e != nil {
+ return nil, e
+ }
+ for rows.Next() {
+ var raw []byte
+ if e = rows.Scan(&raw); e != nil {
+ break
+ }
+ r := RogueRule{Values: map[int][]uint64{}, Decimals: map[int]float64{}}
+ e = wire.Walk(raw, func(f wire.Field) error {
+ switch f.Type {
+ case 0:
+ v, n := binary.Uvarint(f.Value)
+ if n <= 0 {
+ return wire.ErrMalformed
+ }
+ r.Values[f.Number] = append(r.Values[f.Number], v)
+ case 1:
+ if len(f.Value) != 8 {
+ return wire.ErrMalformed
+ }
+ v := math.Float64frombits(binary.LittleEndian.Uint64(f.Value))
+ if math.IsNaN(v) || math.IsInf(v, 0) {
+ return fmt.Errorf("roguelike: nonfinite design")
+ }
+ r.Decimals[f.Number] = v
+ case 2:
+ if slices.Contains(spec.packed, f.Number) {
+ for b := f.Value; len(b) > 0; {
+ v, n := binary.Uvarint(b)
+ if n <= 0 {
+ return wire.ErrMalformed
+ }
+ r.Values[f.Number] = append(r.Values[f.Number], v)
+ b = b[n:]
+ }
+ }
+ }
+ return nil
+ })
+ if e != nil {
+ break
+ }
+ g, id := r.V(spec.g), r.V(spec.id)
+ if spec.g == 0 {
+ g = 0
+ }
+ table.Rows[[2]uint64{g, id}] = r
+ table.Groups[g] = append(table.Groups[g], id)
+ if spec.table == nil {
+ d.Default = r
+ }
+ }
+ if e == nil {
+ e = rows.Err()
+ }
+ _ = rows.Close()
+ if e != nil {
+ return nil, e
+ }
+ for _, ids := range table.Groups {
+ slices.Sort(ids)
+ }
+ if spec.table != nil {
+ *spec.table = table
+ }
+ }
+ stats, e := loadCharacterStatDesign(db)
+ if e != nil {
+ return nil, e
+ }
+ chars := map[uint64]uint64{}
+ rows, e := db.Query("SELECT ProtoBuf FROM CharTable")
+ if e != nil {
+ return nil, e
+ }
+ for rows.Next() {
+ var raw []byte
+ if e = rows.Scan(&raw); e != nil {
+ break
+ }
+ unique, _ := optionalScalar(raw, 20)
+ grade, _ := optionalScalar(raw, 10)
+ temporary, _ := optionalScalar(raw, 21)
+ typ, _ := optionalScalar(raw, 19)
+ id, _ := optionalScalar(raw, 12)
+ if grade == d.Default.V(6) && temporary == 0 && typ == 0 {
+ chars[unique] = id
+ }
+ }
+ if e == nil {
+ e = rows.Err()
+ }
+ _ = rows.Close()
+ if e != nil {
+ return nil, e
+ }
+ bursts, e := loadCostumeBurstDesign(db)
+ if e != nil {
+ return nil, e
+ }
+ visibleDesigns := map[uint64]bool{}
+ collaborationDesigns := map[uint64]bool{}
+ designRows, err := db.Query("SELECT id, ProtoBuf FROM CostumeDesignTable")
+ if err != nil {
+ return nil, err
+ }
+ for designRows.Next() {
+ var id uint64
+ var raw []byte
+ if e = designRows.Scan(&id, &raw); e != nil {
+ break
+ }
+ visibleDesigns[id] = true
+ collaboration, err := optionalScalar(raw, 12)
+ if err != nil {
+ e = err
+ break
+ }
+ collaborationDesigns[id] = collaboration != 0
+ }
+ if e == nil {
+ e = designRows.Err()
+ }
+ _ = designRows.Close()
+ if e != nil {
+ return nil, e
+ }
+ rows, e = db.Query("SELECT ProtoBuf FROM CostumeTable")
+ if e != nil {
+ return nil, e
+ }
+ defer func() { _ = rows.Close() }()
+ for rows.Next() {
+ var raw []byte
+ if e = rows.Scan(&raw); e != nil {
+ return nil, e
+ }
+ usable, _ := optionalScalar(raw, 26)
+ if usable == 0 {
+ continue
+ }
+ id, _ := optionalScalar(raw, 11)
+ designs, err := packedInts(raw, 6)
+ if err != nil {
+ return nil, err
+ }
+ if len(designs) == 0 {
+ return nil, fmt.Errorf("roguelike: costume lacks default design")
+ }
+ if !visibleDesigns[designs[0]] {
+ continue
+ }
+ unique, _ := optionalScalar(raw, 27)
+ maximum, _ := optionalScalar(raw, 15)
+ char := chars[unique]
+ if char == 0 {
+ return nil, fmt.Errorf("roguelike costume %d has no growth character", id)
+ }
+ base, e := stats.BaseStats(char, d.Default.V(7))
+ if e != nil {
+ return nil, e
+ }
+ burst := uint64(len(bursts.Levels[id]))
+ d.Costumes[id] = RogueCostume{ID: id, Unique: unique, Character: char, MaxLevel: maximum, MaxBurst: burst, Health: uint64(base.Health), RequiresOwnership: usable == 2 || collaborationDesigns[designs[0]]}
+ d.CostumeIDs = append(d.CostumeIDs, id)
+ }
+ if e = rows.Err(); e != nil {
+ return nil, e
+ }
+ slices.Sort(d.CostumeIDs)
+ if e = d.loadEnemies(root, version); e != nil {
+ return nil, e
+ }
+ if len(d.CostumeIDs) < int(d.Default.V(42)) || len(d.Levels.Rows) == 0 {
+ return nil, fmt.Errorf("roguelike: incomplete design")
+ }
+ return d, nil
+}
diff --git a/go/internal/server/design/gamedata/roguelike_battle.go b/go/internal/server/design/gamedata/roguelike_battle.go
new file mode 100644
index 0000000..dfee76e
--- /dev/null
+++ b/go/internal/server/design/gamedata/roguelike_battle.go
@@ -0,0 +1,102 @@
+package gamedata
+
+import "fmt"
+
+func (d *RogueLikeDesign) loadEnemies(root, version string) error {
+ db, done, e := openStatDatabase(root, version)
+ if e != nil {
+ return e
+ }
+ defer done()
+ rows, e := db.Query("SELECT id,ProtoBuf FROM PackTable")
+ if e != nil {
+ return e
+ }
+ for rows.Next() {
+ var id uint64
+ var raw []byte
+ if e = rows.Scan(&id, &raw); e != nil {
+ break
+ }
+ kind, _ := optionalScalar(raw, 55)
+ if kind == 4 {
+ d.Pack = id
+ }
+ }
+ if e == nil {
+ e = rows.Err()
+ }
+ _ = rows.Close()
+ if e != nil {
+ return e
+ }
+ if d.Pack == 0 {
+ return fmt.Errorf("roguelike: missing castle pack")
+ }
+ var access []byte
+ if e = db.QueryRow("SELECT ProtoBuf FROM ContentOpenTable WHERE groupId=1 AND id=?", d.Pack).Scan(&access); e != nil {
+ return e
+ }
+ d.PackOpen.TicketID, e = optionalScalar(access, 6)
+ if e != nil {
+ return e
+ }
+ d.PackOpen.SquadLevel, e = optionalScalar(access, 5)
+ if e != nil {
+ return e
+ }
+ pack, closePack, e := OpenDatabase(root, version, fmt.Sprintf("pack%d", d.Pack))
+ if e != nil {
+ return e
+ }
+ defer closePack()
+ wanted := map[uint64]bool{}
+ for _, r := range d.Rooms.Rows {
+ if (r.V(10) >= 1 && r.V(10) <= 3 || r.V(10) == 5 || r.V(10) == 7) && r.V(1) > 0 {
+ wanted[r.V(1)] = true
+ }
+ }
+ d.Enemies = map[uint64][]RogueEnemy{}
+ rows, e = pack.Query("SELECT id,ProtoBuf FROM BattleDeckTable")
+ if e != nil {
+ return e
+ }
+ defer func() { _ = rows.Close() }()
+ for rows.Next() {
+ var id uint64
+ var raw []byte
+ if e = rows.Scan(&id, &raw); e != nil {
+ return e
+ }
+ if !wanted[id] {
+ continue
+ }
+ ids, e := packedInts(raw, 14)
+ if e != nil {
+ return e
+ }
+ levels, e := packedInts(raw, 30)
+ if e != nil {
+ return e
+ }
+ positions, e := packedInts(raw, 32)
+ if e != nil {
+ return e
+ }
+ if len(ids) == 0 || len(ids) != len(levels) || len(ids) != len(positions) {
+ return fmt.Errorf("roguelike: invalid enemy deck %d", id)
+ }
+ for i, c := range ids {
+ d.Enemies[id] = append(d.Enemies[id], RogueEnemy{c, levels[i], positions[i]})
+ }
+ }
+ if e = rows.Err(); e != nil {
+ return e
+ }
+ for id := range wanted {
+ if len(d.Enemies[id]) == 0 {
+ return fmt.Errorf("roguelike: missing enemy deck %d", id)
+ }
+ }
+ return nil
+}
diff --git a/go/internal/server/design/gamedata/source.go b/go/internal/server/design/gamedata/source.go
index 7b03eb4..f5cfdd5 100644
--- a/go/internal/server/design/gamedata/source.go
+++ b/go/internal/server/design/gamedata/source.go
@@ -45,6 +45,7 @@ type Source struct {
fieldMonsterMaps designIndex[int, map[int][]int]
fieldTraps designIndex[int, FieldTrapDesign]
fieldStatues designIndex[int, map[uint64]Reward]
+ questTitles designIndex[int, []QuestTitle]
nPCReputation designIndex[int, NPCReputationDesign]
inns designIndex[int, []InnRule]
waypoint designIndex[uint64, WaypointPack]
@@ -59,6 +60,9 @@ type Source struct {
}
func NewSource(root, version string) *Source { return &Source{root: root, version: version} }
+func (s *Source) QuestTitles(pack int) ([]QuestTitle, error) {
+ return s.questTitles.get(pack, func() ([]QuestTitle, error) { return loadQuestTitles(s.root, s.version, pack) })
+}
func (s *Source) FieldObjects(key int) (FieldObjectDesign, error) {
return s.fieldObjects.get(key, func() (FieldObjectDesign, error) { return LoadFieldObjects(s.root, s.version, key) })
}
diff --git a/go/internal/server/design/gamedata/spine_interaction.go b/go/internal/server/design/gamedata/spine_interaction.go
new file mode 100644
index 0000000..f9458f7
--- /dev/null
+++ b/go/internal/server/design/gamedata/spine_interaction.go
@@ -0,0 +1,118 @@
+package gamedata
+
+import (
+ "fmt"
+
+ "bd2server/internal/server/protocol/wire"
+)
+
+type InteractionPointKey [3]uint64
+
+type InteractionPoint struct {
+ Achievement bool
+ Connected InteractionPointKey
+ RewardGroup uint64
+ Motions map[uint64]bool
+}
+
+type InteractionAccess struct {
+ Provide, Item, Costume, Prestige, Pack uint64
+}
+
+type SpineInteractionDesign struct {
+ Points map[InteractionPointKey]InteractionPoint
+ Rewards map[uint64][]Reward
+ Access map[uint64][]InteractionAccess
+ RecordGroups map[uint64]bool
+ RecordTools map[uint64]bool
+ RecordSaveSlots, MaxRecordTime, MaxRecordInteractions uint64
+}
+
+func LoadSpineInteractionDesign(root, version string) (*SpineInteractionDesign, error) {
+ db, closeDB, err := openStatDatabase(root, version)
+ if err != nil {
+ return nil, err
+ }
+ defer closeDB()
+ d := &SpineInteractionDesign{Points: map[InteractionPointKey]InteractionPoint{}, Rewards: map[uint64][]Reward{}, Access: map[uint64][]InteractionAccess{}}
+ read := func(table string, visit func([]byte) error) error { return readCashMetadata(db, table, visit) }
+ d.RecordGroups = map[uint64]bool{}
+ d.RecordTools = map[uint64]bool{}
+ if err := read("SpineInteractionTable", func(raw []byte) error {
+ id, _, err := wire.Varint(raw, 3)
+ if err != nil || id == 0 {
+ return fmt.Errorf("gamedata: invalid interaction recording group")
+ }
+ d.RecordGroups[id] = true
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if err := read("SpineInteractionToolbarTable", func(raw []byte) error {
+ id, _, err := wire.Varint(raw, 2)
+ if err != nil {
+ return err
+ }
+ d.RecordTools[id] = true
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ defaults := 0
+ if err := read("SpineInteractionDefaultTable", func(raw []byte) error {
+ defaults++
+ d.RecordSaveSlots, _, _ = wire.Varint(raw, 12)
+ d.MaxRecordTime, _, _ = wire.Varint(raw, 7)
+ d.MaxRecordInteractions, _, _ = wire.Varint(raw, 6)
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if defaults != 1 || d.RecordSaveSlots == 0 || d.MaxRecordTime == 0 || d.MaxRecordInteractions == 0 {
+ return nil, fmt.Errorf("gamedata: invalid interaction recording limits")
+ }
+ if err := read("SpineInteractionPointTable", func(raw []byte) error {
+ v := func(field int) uint64 { n, _, _ := wire.Varint(raw, field); return n }
+ key := InteractionPointKey{v(8), v(5), v(6)}
+ if key[0] == 0 || key[1] == 0 || key[2] == 0 {
+ return fmt.Errorf("gamedata: invalid interaction point")
+ }
+ d.Points[key] = InteractionPoint{Achievement: v(1) != 0, Connected: InteractionPointKey{key[0], v(3), v(4)}, RewardGroup: v(21), Motions: map[uint64]bool{}}
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if err := read("InteractionAchievementTable", func(raw []byte) error {
+ v := func(field int) uint64 { n, _, _ := wire.Varint(raw, field); return n }
+ key := InteractionPointKey{v(3), v(1), v(2)}
+ point, exists := d.Points[key]
+ if !exists {
+ return fmt.Errorf("gamedata: interaction motion has no point %v", key)
+ }
+ point.Motions[v(4)] = true
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if err := read("InteractionRewardGroupTable", func(raw []byte) error {
+ v := func(field int) uint64 { n, _, _ := wire.Varint(raw, field); return n }
+ r := Reward{Type: v(5), ID: v(4), Count: v(3)}
+ if v(1) == 0 || r.Type == 0 || r.Count == 0 {
+ return fmt.Errorf("gamedata: invalid interaction reward")
+ }
+ d.Rewards[v(1)] = append(d.Rewards[v(1)], r)
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ if err := read("LobbySettingItemTable", func(raw []byte) error {
+ v := func(field int) uint64 { n, _, _ := wire.Varint(raw, field); return n }
+ if group := v(4); group != 0 {
+ d.Access[group] = append(d.Access[group], InteractionAccess{Provide: v(10), Item: v(3), Costume: v(1), Prestige: v(9), Pack: v(8)})
+ }
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ return d, nil
+}
diff --git a/go/internal/server/design/gamedata/total_war_enemy.go b/go/internal/server/design/gamedata/total_war_enemy.go
new file mode 100644
index 0000000..ad321e8
--- /dev/null
+++ b/go/internal/server/design/gamedata/total_war_enemy.go
@@ -0,0 +1,59 @@
+package gamedata
+
+import "fmt"
+
+type TotalWarEnemy struct{ ID, Level, Grid uint64 }
+
+func loadTotalWarEnemies(root, version string) ([]TotalWarEnemy, error) {
+ db, done, err := openStatDatabase(root, version)
+ if err != nil {
+ return nil, err
+ }
+ var pack uint64
+ err = castleRows(db, "PackTable", func(id uint64, raw []byte) error {
+ typ, err := optionalScalar(raw, 55)
+ if err != nil {
+ return err
+ }
+ if typ == 7 {
+ if pack != 0 {
+ return fmt.Errorf("gamedata: multiple total war packs")
+ }
+ pack = id
+ }
+ return nil
+ })
+ done()
+ if err != nil || pack == 0 {
+ return nil, fmt.Errorf("gamedata: total war pack unavailable: %v", err)
+ }
+ db, done, err = openPackDatabase(root, version, int(pack))
+ if err != nil {
+ return nil, err
+ }
+ defer done()
+ var raw []byte
+ if err := db.QueryRow("SELECT ProtoBuf FROM BattleDeckTable WHERE id=1").Scan(&raw); err != nil {
+ return nil, err
+ }
+ ids, err := packedInts(raw, 14)
+ if err != nil {
+ return nil, err
+ }
+ levels, err := packedInts(raw, 30)
+ if err != nil {
+ return nil, err
+ }
+ positions, err := packedInts(raw, 32)
+ if err != nil || len(ids) == 0 || len(ids) != len(levels) || len(ids) != len(positions) {
+ return nil, fmt.Errorf("gamedata: invalid total war enemies")
+ }
+ var out []TotalWarEnemy
+ for i, id := range ids {
+ if id == 0 || levels[i] == 0 {
+ return nil, fmt.Errorf("gamedata: invalid total war enemy")
+ }
+ out = append(out, TotalWarEnemy{ID: id, Level: levels[i], Grid: positions[i]})
+ }
+ return out, nil
+}
diff --git a/go/internal/server/design/gamedata/total_war_presets.go b/go/internal/server/design/gamedata/total_war_presets.go
new file mode 100644
index 0000000..cccb344
--- /dev/null
+++ b/go/internal/server/design/gamedata/total_war_presets.go
@@ -0,0 +1,29 @@
+package gamedata
+
+import "fmt"
+
+func loadTotalWarPresetDesign(root, version string) (*PresetDesign, error) {
+ db, release, err := OpenDatabase(root, version, "common")
+ if err != nil {
+ return nil, err
+ }
+ defer release()
+ d, err := loadPresetDesign(db)
+ if err != nil {
+ return nil, err
+ }
+ var raw []byte
+ if err = db.QueryRow("SELECT ProtoBuf FROM GameDefaultTable WHERE id=0").Scan(&raw); err != nil {
+ return nil, err
+ }
+ if d.BaseCount, err = optionalScalar(raw, 114); err != nil {
+ return nil, err
+ }
+ if d.Maximum, err = optionalScalar(raw, 115); err != nil {
+ return nil, err
+ }
+ if err = d.Validate(); err != nil {
+ return nil, fmt.Errorf("gamedata: total war presets: %w", err)
+ }
+ return d, nil
+}
diff --git a/go/internal/server/domain/battle/castle/battle.go b/go/internal/server/domain/battle/castle/battle.go
new file mode 100644
index 0000000..8d3d8cd
--- /dev/null
+++ b/go/internal/server/domain/battle/castle/battle.go
@@ -0,0 +1,266 @@
+package castle
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "fmt"
+ "math"
+ "slices"
+)
+
+func (s *Service) HandlesBattle(mode uint64) bool {
+ return mode == 7 || mode == 16 || mode == 19 || mode == 20
+}
+func (s *Service) EnterBattle(ctx command.Context, req []byte, identity string) ([]byte, error) {
+ v, season, active, e := s.load(ctx)
+ if e != nil {
+ return nil, e
+ }
+ mode, deck := n(req, 5), n(req, 4)
+ if !s.HandlesBattle(mode) || identity == "" {
+ return nil, fmt.Errorf("castle: invalid castle encounter")
+ }
+ if s.currentPack == nil {
+ return nil, fmt.Errorf("castle: current pack unavailable")
+ }
+ pack, e := s.currentPack(ctx)
+ if e != nil {
+ return nil, e
+ }
+ if uint64(pack) != s.design.PackID {
+ return nil, fmt.Errorf("castle: not in castle pack")
+ }
+ a := &encounter{Mode: mode, Deck: deck, Monster: n(req, 3), Receipt: identity, Season: season}
+ if mode == 7 {
+ if !active || v.Run == nil {
+ return nil, fmt.Errorf("castle: no active pride floor")
+ }
+ f, ok := s.design.Floors[v.Run.Floor]
+ if !ok || f.Monsters[a.Monster] != deck || v.Run.Cleared[a.Monster] {
+ return nil, fmt.Errorf("castle: invalid pride monster/deck")
+ }
+ if a.Monster == f.Boss {
+ for monster := range f.Monsters {
+ if monster != f.Boss && !v.Run.Cleared[monster] {
+ return nil, fmt.Errorf("castle: pride boss locked")
+ }
+ }
+ }
+ a.ID = f.ID
+ } else {
+ id := n(req, 9)
+ t, ok := s.design.Towers[[2]uint64{mode, id}]
+ if !ok || t.Deck != deck {
+ return nil, fmt.Errorf("castle: invalid tower/deck")
+ }
+ if t.Previous != 0 {
+ if _, ok = v.Towers[towerKey(mode, t.Previous)]; !ok {
+ return nil, fmt.Errorf("castle: tower floor locked")
+ }
+ }
+ a.ID = id
+ }
+ v.Encounter = a
+ return nil, save(ctx, v)
+}
+
+func (s *Service) AbandonBattle(ctx command.Context) error {
+ v, _, _, e := s.load(ctx)
+ if e != nil {
+ return e
+ }
+ v.Encounter = nil
+ return save(ctx, v)
+}
+
+func (s *Service) CompleteBattle(ctx command.Context, req []byte, identity string) ([]byte, error) {
+ v, season, active, e := s.load(ctx)
+ if e != nil {
+ return nil, e
+ }
+ a := v.Encounter
+ if a == nil || a.Receipt != identity || s.evidence == nil {
+ return nil, fmt.Errorf("castle: settlement has no castle encounter")
+ }
+ proof := s.evidence(ctx)
+ if proof.Receipt != identity || proof.Mode != a.Mode || proof.Deck != a.Deck || proof.Monster != a.Monster || proof.Round == 0 {
+ return nil, fmt.Errorf("castle: settlement has no started battle")
+ }
+ key := fmt.Sprintf("battle:%s:%d", identity, proof.Attempt)
+ if out, ok, e := loadReceipt(ctx, key, req); e != nil || ok {
+ return out, e
+ }
+ win := n(req, 2) == 1
+ var out []byte
+ if win {
+ deck, ok := s.design.Decks[a.Deck]
+ if !ok {
+ return nil, fmt.Errorf("castle: missing deck design")
+ }
+ final, e := msgs(req, 3)
+ if e != nil {
+ return nil, e
+ }
+ alive := map[uint64]bool{}
+ participants := map[uint64]uint64{}
+ finalSeen := map[uint64]bool{}
+ var party []Participant
+ for _, raw := range proof.InitialBlue {
+ index, id := n(raw, 2), n(raw, 3)
+ if index == 0 || id == 0 || participants[index] != 0 {
+ return nil, fmt.Errorf("castle: invalid initial party")
+ }
+ participants[index] = id
+ party = append(party, Participant{index, n(raw, 6), id, n(raw, 7)})
+ }
+ if len(participants) == 0 || len(participants) > 5 {
+ return nil, fmt.Errorf("castle: invalid castle party size")
+ }
+ if s.validate == nil {
+ return nil, fmt.Errorf("castle: ownership validation unavailable")
+ }
+ if e = s.validate(ctx, party); e != nil {
+ return nil, e
+ }
+ for _, raw := range final {
+ index := n(raw, 1)
+ if _, ok := participants[index]; !ok || finalSeen[index] || n(raw, 2) != participants[index] || n(raw, 3) > math.MaxInt64 {
+ return nil, fmt.Errorf("castle: invalid settlement party")
+ }
+ alive[index] = n(raw, 3) > 0
+ finalSeen[index] = true
+ }
+ if len(final) != len(participants) {
+ return nil, fmt.Errorf("castle: missing settlement party")
+ }
+ definitions := make([]gamedata.EventBattleChallenge, len(deck.Challenges))
+ for i, c := range deck.Challenges {
+ definitions[i] = gamedata.EventBattleChallenge{Type: c.Type, Value1: c.Value1, Value2: c.Value2}
+ }
+ indexes, e := gamedata.VerifySubmittedChallenges(req, definitions)
+ if e != nil {
+ return nil, e
+ }
+ var bonus uint64
+ for _, index := range indexes {
+ c := deck.Challenges[index]
+ satisfied := true
+ switch c.Type {
+ case 1, 3:
+ satisfied = false
+ for id, char := range participants {
+ if s.design.Characters[char].Unique == c.Value1 && (c.Type == 1 || alive[id]) {
+ satisfied = true
+ }
+ }
+ case 2:
+ satisfied = proof.Round <= c.Value1
+ case 4, 5:
+ count := uint64(0)
+ for _, char := range participants {
+ if s.design.Characters[char].Element == c.Value1 {
+ count++
+ }
+ }
+ satisfied = (c.Type == 4 && count >= c.Value2) || (c.Type == 5 && count <= c.Value2)
+ case 7:
+ dead := uint64(0)
+ for id := range participants {
+ if !alive[id] {
+ dead++
+ }
+ }
+ satisfied = dead < c.Value1
+ }
+ if !satisfied {
+ return nil, fmt.Errorf("castle: contradicted challenge claim")
+ }
+ if bonus > math.MaxInt32-c.Score {
+ return nil, fmt.Errorf("castle: challenge score overflow")
+ }
+ bonus += c.Score
+ }
+ if a.Mode == 7 {
+ if !active || a.Season != season || v.Run == nil || v.Run.Floor != a.ID {
+ return nil, fmt.Errorf("castle: pride season/run changed")
+ }
+ f := s.design.Floors[a.ID]
+ survived := uint64(0)
+ for _, live := range alive {
+ if live {
+ survived++
+ }
+ }
+ sc := f.Scoring
+ // GetEvaluationPoint uses single-precision intermediate truncation.
+ evaluation := uint64(float32(1)/float32(proof.Round+9)*10*float32(sc.Turn)) + uint64(float32(survived)/5*float32(sc.Survival)) + uint64(float32(1)/float32(v.Run.Retry+proof.Attempt+1)*float32(sc.Retry))
+ if a.Monster == f.Boss {
+ evaluation = uint64(math.RoundToEven(float64(evaluation) * math.Trunc(sc.BossMultiplier*100) / 100))
+ }
+ points := bonus + sc.Base + evaluation
+ if points > math.MaxInt32 || v.Run.Point > math.MaxInt32-points {
+ return nil, fmt.Errorf("castle: floor score overflow")
+ }
+ v.Run.Point += points
+ v.Run.Cleared[a.Monster] = true
+ progress := v.Floors[a.ID]
+ progress.ID = a.ID
+ progress.Point = v.Run.Point
+ progress.Retry = v.Run.Retry
+ if a.Monster == f.Boss {
+ if progress.Point > progress.Highest {
+ progress.Highest = progress.Point
+ progress.Achieved = uint64(s.now().UnixMilli())
+ }
+ v.Run = nil
+ }
+ v.Floors[a.ID] = progress
+ out = wire.AppendBytes(out, 10, floorWire(progress))
+ out = wire.AppendBytes(out, 11, totalWire(v))
+ out = wire.AppendVarint(out, 12, evaluation)
+ monster := wire.AppendVarint(nil, 1, a.Monster)
+ monster = wire.AppendVarint(monster, 2, a.Deck)
+ out = wire.AppendBytes(out, 4, monster)
+ } else {
+ key := towerKey(a.Mode, a.ID)
+ previous := v.Towers[key]
+ current := previous
+ current.ID, current.Mode = a.ID, a.Mode
+ var rewards []gamedata.Reward
+ if previous.ID == 0 {
+ rewards = append(rewards, deck.Rewards...)
+ }
+ for _, index := range indexes {
+ if !slices.Contains(current.Challenges, index) {
+ current.Challenges = append(current.Challenges, index)
+ r := deck.Challenges[index].Reward
+ if r.Type != 0 && r.Count != 0 {
+ rewards = append(rewards, r)
+ }
+ }
+ }
+ slices.Sort(current.Challenges)
+ if len(rewards) > 0 {
+ if s.grant == nil {
+ return nil, fmt.Errorf("castle: reward grant unavailable")
+ }
+ bundle, e := s.grant(ctx, "castle:tower:"+key+":"+identity, rewards)
+ if e != nil {
+ return nil, e
+ }
+ out = wire.AppendBytes(out, 5, bundle)
+ }
+ v.Towers[key] = current
+ out = wire.AppendBytes(out, 15, towerWire(current))
+ }
+ }
+ v.Encounter = nil
+ if e = save(ctx, v); e != nil {
+ return nil, e
+ }
+ if e = putReceipt(ctx, key, req, out); e != nil {
+ return nil, e
+ }
+ return out, nil
+}
diff --git a/go/internal/server/domain/battle/castle/progress_test.go b/go/internal/server/domain/battle/castle/progress_test.go
new file mode 100644
index 0000000..3a35f37
--- /dev/null
+++ b/go/internal/server/domain/battle/castle/progress_test.go
@@ -0,0 +1,252 @@
+package castle
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/battle"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+ "fmt"
+ "testing"
+ "time"
+)
+
+func request(seq uint64, fields ...uint64) []byte {
+ out := wire.AppendVarint(nil, 1, seq)
+ for i, v := range fields {
+ out = wire.AppendVarint(out, i+2, v)
+ }
+ return out
+}
+func execute(t *testing.T, s *Service, ctx command.Context, path string, req []byte) []byte {
+ t.Helper()
+ _, out, handled, e := s.Handle(ctx, path, req)
+ if e != nil || !handled {
+ t.Fatalf("%s: handled=%v error=%v", path, handled, e)
+ }
+ return out
+}
+func testDesign() *gamedata.CastleRewardDesign {
+ return &gamedata.CastleRewardDesign{
+ TotalWarEnemies: []gamedata.TotalWarEnemy{{ID: 95, Level: 1}},
+ PackID: 31,
+ Towers: map[[2]uint64]gamedata.CastleTower{{16, 1}: {Mode: 16, ID: 1, Deck: 61}, {16, 2}: {Mode: 16, ID: 2, Previous: 1, Deck: 62}},
+ Floors: map[uint64]gamedata.CastleFloor{1: {ID: 1, Boss: 52, Monsters: map[uint64]uint64{51: 61, 52: 62}, Scoring: gamedata.CastleScoring{Base: 10, Turn: 100, Survival: 100, BossMultiplier: 2}}},
+ Decks: map[uint64]gamedata.CastleDeck{61: {ID: 61, Challenges: []gamedata.CastleChallenge{{Type: 8, Reward: gamedata.Reward{Type: 4, Count: 10}}}}, 62: {ID: 62}},
+ Characters: map[uint64]gamedata.CastleCharacter{71: {Unique: 71, Element: 1}},
+ Daily: []gamedata.ScoreReward{{ID: 1, Score: 100, Reward: gamedata.Reward{Type: 4, Count: 1}}, {ID: 2, Score: 350, Reward: gamedata.Reward{Type: 4, Count: 3}}},
+ TotalWarDaily: []gamedata.ScoreReward{{ID: 1, Score: 50, Reward: gamedata.Reward{Type: 4, Count: 1}}, {ID: 2, Score: 100, Reward: gamedata.Reward{Type: 4, Count: 3}}},
+ Reset: gamedata.FieldResetSchedule{DailyReset: 9 * time.Hour},
+ }
+}
+
+func TestBattleProgressReopenAccountsAndDailySeasonIsolation(t *testing.T) {
+ d := testDesign()
+ now := time.Date(2026, 10, 17, 1, 0, 0, 0, time.UTC)
+ season := uint64(1)
+ proof := battle.SettlementEvidence{}
+ balances := map[string]map[[2]uint64]uint64{}
+ gold := func(account string) uint64 { return balances[account][[2]uint64{4, 0}] }
+ configure := func() *Service {
+ s := NewService(d)
+ s.AttachClock(func() time.Time { return now })
+ s.AttachPeriod(func(command.Context) (uint64, bool, error) { return season, true, nil })
+ s.AttachCurrentPack(func(command.Context) (int, error) { return int(d.PackID), nil })
+ s.AttachEvidence(func(command.Context) battle.SettlementEvidence { return proof })
+ s.AttachTotalWarValidation(func(_ command.Context, ps []Participant) error {
+ for _, p := range ps {
+ if p.CharacterIndex != 81 || p.CostumeID != 91 {
+ return fmt.Errorf("not owned")
+ }
+ }
+ return nil
+ })
+ s.AttachRewards(func(ctx command.Context, _ string, rewards []gamedata.Reward) ([]byte, error) {
+ if balances[ctx.AccountID] == nil {
+ balances[ctx.AccountID] = map[[2]uint64]uint64{}
+ }
+ for _, r := range rewards {
+ balances[ctx.AccountID][[2]uint64{r.Type, r.ID}] += r.Count
+ }
+ return nil, nil
+ })
+ return s
+ }
+ s := configure()
+ a := command.Context{Identity: command.Identity{AccountID: "a", SessionID: "a-session"}, State: stateio.NewMemory()}
+ b := command.Context{Identity: command.Identity{AccountID: "b", SessionID: "b-session"}, State: stateio.NewMemory()}
+ if out := execute(t, s, a, "/EvilCastleTowerInfo", request(1)); len(out) != 0 {
+ t.Fatal("unplayed tower has progress")
+ }
+ if _, e := s.EnterBattle(a, request(2, 0, 0, 62, 16, 0, 0, 0, 2), "locked"); e == nil {
+ t.Fatal("entered locked tower floor")
+ }
+ enter := request(3, 0, 0, 61, 16, 0, 0, 0, 1)
+ if _, e := s.EnterBattle(a, enter, "tower"); e != nil {
+ t.Fatal(e)
+ }
+ blue := wire.AppendVarint(nil, 2, 81)
+ blue = wire.AppendVarint(blue, 3, 71)
+ blue = wire.AppendVarint(blue, 6, 82)
+ blue = wire.AppendVarint(blue, 7, 91)
+ proof = battle.SettlementEvidence{Receipt: "tower", Mode: 16, Deck: 61, Round: 1, InitialBlue: [][]byte{blue}}
+ end := wire.AppendVarint(request(4, 1), 5, 0)
+ char := wire.AppendVarint(nil, 1, 81)
+ char = wire.AppendVarint(char, 2, 71)
+ char = wire.AppendVarint(char, 3, 1)
+ end = wire.AppendBytes(end, 3, char)
+ if _, e := s.CompleteBattle(a, end, "tower"); e != nil {
+ t.Fatal(e)
+ }
+ if gold("a") != 10 || gold("b") != 0 {
+ t.Fatal("tower challenge reward was not credited once to its account")
+ }
+ s = configure()
+ a.SessionID = "reopened"
+ assertTower := func(seq uint64) {
+ t.Helper()
+ rows, e := msgs(execute(t, s, a, "/EvilCastleTowerInfo", request(seq)), 1)
+ if e != nil || len(rows) != 1 || n(rows[0], 1) != 1 || n(rows[0], 3) != 16 {
+ t.Fatal("reopened tower has the wrong floor or mode")
+ }
+ index, present, e := wire.Varint(rows[0], 2)
+ if e != nil || !present || index != 0 {
+ t.Fatal("reopened tower lost its completed victory challenge")
+ }
+ }
+ assertTower(5)
+ if out := execute(t, s, b, "/EvilCastleTowerInfo", request(5)); len(out) != 0 {
+ t.Fatal("account tower isolation failed")
+ }
+ start := request(6, 1)
+ twchar := wire.AppendVarint(blue, 1, 1)
+ start = wire.AppendBytes(start, 3, twchar)
+ red := wire.AppendVarint(nil, 1, 2)
+ red = wire.AppendVarint(red, 3, 95)
+ red = wire.AppendVarint(red, 4, 1000000)
+ red = wire.AppendVarint(red, 5, 1)
+ start = wire.AppendBytes(start, 4, red)
+ execute(t, s, a, "/TotalWarBattleStart", start)
+ scoreBody := wire.AppendVarint(nil, 1, 91)
+ scoreBody = wire.AppendVarint(scoreBody, 2, 100)
+ twEnd := wire.AppendBytes(request(7), 2, scoreBody)
+ execute(t, s, a, "/TotalWarBattleEnd", twEnd)
+ if n(execute(t, s, a, "/TotalWarRewardState", request(8)), 1) != 1 {
+ t.Fatal("scored total war reward unavailable")
+ }
+ if n(execute(t, s, b, "/TotalWarRewardState", request(8)), 1) != 0 {
+ t.Fatal("account reward isolation failed")
+ }
+ claim := request(9)
+ execute(t, s, a, "/TotalWarReward", claim)
+ execute(t, s, a, "/TotalWarReward", claim)
+ if gold("a") != 13 {
+ t.Fatal("100 damage did not select the 3-gold tier exactly once")
+ }
+ if n(execute(t, s, a, "/TotalWarRewardState", request(10)), 1) != 0 {
+ t.Fatal("claimed total war reward available")
+ }
+ a.SessionID = "second-login-same-day"
+ if _, _, _, e := s.Handle(a, "/TotalWarReward", request(110)); e == nil || gold("a") != 13 {
+ t.Fatal("same-day new login claimed the daily reward again")
+ }
+ now = now.Add(24 * time.Hour)
+ s = configure()
+ if n(execute(t, s, a, "/TotalWarRewardState", request(11)), 1) != 1 {
+ t.Fatal("next day total war reward unavailable")
+ }
+ execute(t, s, a, "/TotalWarReward", request(111))
+ if gold("a") != 16 || n(execute(t, s, a, "/TotalWarRewardState", request(112)), 1) != 0 {
+ t.Fatal("new day did not credit exactly one renewed daily reward")
+ }
+ for _, monster := range []uint64{51, 52} {
+ execute(t, s, a, "/EvilCastleEnter", request(12+monster, d.PackID, 1))
+ deck := d.Floors[1].Monsters[monster]
+ id := fmt.Sprint(monster)
+ if _, e := s.EnterBattle(a, request(20+monster, 0, monster, deck, 7), id); e != nil {
+ t.Fatal(e)
+ }
+ proof = battle.SettlementEvidence{Receipt: id, Mode: 7, Deck: deck, Monster: monster, Round: 1, InitialBlue: [][]byte{blue}}
+ end := wire.AppendBytes(request(30+monster, 1), 3, char)
+ if _, e := s.CompleteBattle(a, end, id); e != nil {
+ t.Fatal(e)
+ }
+ }
+ // One surviving hero at turn 1 earns 100 turn + 20 survival points.
+ // The ordinary encounter scores 10+120; the boss scores 10+2*120.
+ // Their independently computed total is 380, above the 350-point tier.
+ info := execute(t, s, a, "/EvilCastleInfo", request(99))
+ floors, e := msgs(info, 1)
+ totals, te := msgs(info, 2)
+ if e != nil || te != nil || len(floors) != 1 || len(totals) != 1 || n(floors[0], 2) != 1 || n(floors[0], 4) != 380 || n(floors[0], 5) != 380 || n(totals[0], 2) != 380 {
+ t.Fatal("floor best and cumulative score disagree with the played encounters")
+ }
+ if n(execute(t, s, a, "/EvilCastleDailyRewardState", request(100)), 1) != 1 {
+ t.Fatal("cleared floor reward unavailable")
+ }
+ execute(t, s, a, "/EvilCastleDailyReward", request(101))
+ if gold("a") != 19 {
+ t.Fatal("380 pride points did not credit the 3-gold daily tier")
+ }
+ if n(execute(t, s, a, "/EvilCastleDailyRewardState", request(102)), 1) != 0 {
+ t.Fatal("castle claim not recorded")
+ }
+ season++
+ now = now.Add(24 * time.Hour)
+ if n(execute(t, s, a, "/EvilCastleDailyRewardState", request(103)), 1) != 0 {
+ t.Fatal("expired season score granted reward")
+ }
+ newInfo := execute(t, s, a, "/EvilCastleInfo", request(105))
+ newFloors, _ := msgs(newInfo, 1)
+ newTotals, _ := msgs(newInfo, 2)
+ if n(newInfo, 3) != 2 || len(newFloors) != 0 || len(newTotals) != 1 || n(newTotals[0], 2) != 0 || gold("a") != 19 || gold("b") != 0 {
+ t.Fatal("new season retained expired score or changed account rewards")
+ }
+ assertTower(104)
+}
+
+func TestTotalWarRejectsUnstartedAndUnregisteredDamage(t *testing.T) {
+ d := testDesign()
+ s := NewService(d)
+ s.AttachTotalWarValidation(func(_ command.Context, ps []Participant) error {
+ for _, p := range ps {
+ if p.CostumeID != 91 && p.CostumeID != 92 {
+ return fmt.Errorf("not owned")
+ }
+ }
+ return nil
+ })
+ ctx := command.Context{Identity: command.Identity{SessionID: "session"}, State: stateio.NewMemory()}
+ end := wire.AppendBytes(request(1), 2, request(91, 100))
+ if _, _, _, e := s.Handle(ctx, "/TotalWarBattleEnd", end); e == nil {
+ t.Fatal("unstarted damage accepted")
+ }
+ char := wire.AppendVarint(nil, 1, 1)
+ char = wire.AppendVarint(char, 2, 81)
+ char = wire.AppendVarint(char, 3, 71)
+ char = wire.AppendVarint(char, 6, 82)
+ char = wire.AppendVarint(char, 7, 91)
+ cheer := wire.AppendVarint(nil, 2, 81)
+ cheer = wire.AppendVarint(cheer, 3, 71)
+ cheer = wire.AppendVarint(cheer, 6, 83)
+ cheer = wire.AppendVarint(cheer, 7, 92)
+ cheer = wire.AppendVarint(cheer, 28, 1)
+ start := wire.AppendBytes(request(2, 1), 3, char)
+ start = wire.AppendBytes(start, 3, cheer)
+ red := wire.AppendVarint(nil, 1, 2)
+ red = wire.AppendVarint(red, 3, 95)
+ red = wire.AppendVarint(red, 4, 1000000)
+ red = wire.AppendVarint(red, 5, 1)
+ start = wire.AppendBytes(start, 4, red)
+ execute(t, s, ctx, "/TotalWarBattleStart", start)
+ bad := wire.AppendBytes(request(3), 2, request(92, 100))
+ if _, _, _, e := s.Handle(ctx, "/TotalWarBattleEnd", bad); e == nil {
+ t.Fatal("cheering costume damage accepted")
+ }
+ good := wire.AppendBytes(request(4), 2, request(91, 100))
+ execute(t, s, ctx, "/TotalWarBattleEnd", good)
+ stored, e := msgs(execute(t, s, ctx, "/TotalWarInfo", request(5)), 1)
+ if e != nil || len(stored) != 1 || n(stored[0], 1) != 91 || n(stored[0], 2) != 100 {
+ t.Fatal("rejected damage consumed the active battle or changed its legitimate saved damage")
+ }
+}
diff --git a/go/internal/server/domain/battle/castle/ranking.go b/go/internal/server/domain/battle/castle/ranking.go
new file mode 100644
index 0000000..f3dde3b
--- /dev/null
+++ b/go/internal/server/domain/battle/castle/ranking.go
@@ -0,0 +1,271 @@
+package castle
+
+import (
+ "encoding/json"
+ "fmt"
+ "slices"
+ "strconv"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+)
+
+type RankProfile struct {
+ Owner, XP, Portrait, PortraitDesign, Title uint64
+ Name string
+ Guild []byte
+}
+type RankRecord struct{ Season, Stage, Point, Date uint64 }
+type RankEntry struct {
+ RankRecord
+ Profile RankProfile
+ Rank uint64
+}
+type RankPublication struct {
+ Account string
+ Version uint64
+ Profile RankProfile
+ Records []RankRecord
+}
+type RankSource interface {
+ Top(season, stage uint64, limit int) []RankEntry
+ Rank(owner uint64, record RankRecord) RankEntry
+}
+
+func (s *Service) AttachRanking(owner uint64, source RankSource) {
+ s.rankOwner, s.rankSource = owner, source
+}
+func (s *Service) AttachSeasonSettlement(f func(uint64) bool) { s.settled = f }
+func RankWire(entry RankEntry) []byte {
+ p := entry.Profile
+ out := wire.AppendVarint(nil, 1, p.Owner)
+ out = wire.AppendString(out, 2, p.Name)
+ for f, v := range map[int]uint64{3: p.XP, 4: p.Portrait, 5: p.PortraitDesign, 7: entry.Rank, 8: entry.Point, 9: p.Title, 10: entry.Date} {
+ out = wire.AppendVarint(out, f, v)
+ }
+ return wire.AppendBytes(out, 6, p.Guild)
+}
+func (s *Service) seasonFloors(ctx command.Context, v *state) (map[uint64]map[uint64]floor, error) {
+ rows, e := ctx.State.ListEntries("missions", "castle_seasons")
+ if e != nil {
+ return nil, e
+ }
+ out := map[uint64]map[uint64]floor{}
+ for key, raw := range rows {
+ season, e := strconv.ParseUint(key, 10, 64)
+ if e != nil || season == 0 {
+ return nil, fmt.Errorf("castle: invalid season history")
+ }
+ var floors map[uint64]floor
+ if e = json.Unmarshal(raw, &floors); e != nil {
+ return nil, e
+ }
+ out[season] = floors
+ }
+ if v.Season != 0 {
+ out[v.Season] = v.Floors
+ }
+ return out, nil
+}
+func recordsFor(season uint64, floors map[uint64]floor) []RankRecord {
+ var out []RankRecord
+ var total, date uint64
+ for stage, f := range floors {
+ if f.Highest == 0 {
+ continue
+ }
+ out = append(out, RankRecord{season, stage, f.Highest, f.Achieved})
+ total += f.Highest
+ date = max(date, f.Achieved)
+ }
+ if total != 0 {
+ out = append(out, RankRecord{season, 0, total, date})
+ }
+ return out
+}
+func (s *Service) RankRecords(ctx command.Context) ([]RankRecord, error) {
+ v, _, _, e := s.load(ctx)
+ if e != nil {
+ return nil, e
+ }
+ seasons, e := s.seasonFloors(ctx, v)
+ if e != nil {
+ return nil, e
+ }
+ var out []RankRecord
+ for season, floors := range seasons {
+ out = append(out, recordsFor(season, floors)...)
+ }
+ slices.SortFunc(out, func(a, b RankRecord) int {
+ if a.Season != b.Season {
+ return cmp(a.Season, b.Season)
+ }
+ return cmp(a.Stage, b.Stage)
+ })
+ return out, nil
+}
+func cmp(a, b uint64) int {
+ if a < b {
+ return -1
+ }
+ if a > b {
+ return 1
+ }
+ return 0
+}
+func (s *Service) placed(record RankRecord) (RankEntry, error) {
+ if record.Point == 0 {
+ return RankEntry{RankRecord: record}, nil
+ }
+ if s.rankSource == nil {
+ return RankEntry{}, fmt.Errorf("castle: ranking unavailable")
+ }
+ return s.rankSource.Rank(s.rankOwner, record), nil
+}
+func (s *Service) rankInfo(ctx command.Context, v *state, path string, req []byte) ([]byte, error) {
+ if n(req, 2) != s.design.PackID {
+ return nil, fmt.Errorf("castle: invalid ranking pack")
+ }
+ season, stage := n(req, 3), n(req, 4)
+ if season == 0 {
+ season = v.Season
+ }
+ if stage != 0 {
+ if _, ok := s.design.Floors[stage]; !ok {
+ return nil, fmt.Errorf("castle: invalid ranking stage")
+ }
+ }
+ seasons, e := s.seasonFloors(ctx, v)
+ if e != nil {
+ return nil, e
+ }
+ records := recordsFor(season, seasons[season])
+ var own, total RankEntry
+ for _, record := range records {
+ if record.Stage != stage && record.Stage != 0 {
+ continue
+ }
+ entry, e := s.placed(record)
+ if e != nil {
+ return nil, e
+ }
+ if record.Stage == stage {
+ own = entry
+ }
+ if record.Stage == 0 {
+ total = entry
+ }
+ }
+ var out []byte
+ if path == "/EvilCastleStageRankingInfo" {
+ for field, value := range map[int]uint64{1: own.Rank, 2: own.Point, 3: total.Rank, 4: total.Point} {
+ out = wire.AppendVarint(out, field, value)
+ }
+ return out, nil
+ }
+ if s.rankSource == nil {
+ return nil, fmt.Errorf("castle: ranking unavailable")
+ }
+ for _, entry := range s.rankSource.Top(season, stage, 100) {
+ out = wire.AppendBytes(out, 1, RankWire(entry))
+ }
+ if own.Point != 0 {
+ out = wire.AppendBytes(out, 2, RankWire(own))
+ }
+ return out, nil
+}
+func castleRankRewards(rows []gamedata.CastleRankReward, rank uint64) []gamedata.Reward {
+ var out []gamedata.Reward
+ if rank == 0 {
+ return nil
+ }
+ for _, r := range rows {
+ if r.Rank > rank {
+ break
+ }
+ out = r.Rewards
+ }
+ return out
+}
+func rewardWire(r gamedata.Reward) []byte {
+ out := wire.AppendVarint(nil, 1, r.ID)
+ out = wire.AppendVarint(out, 2, r.Type)
+ return wire.AppendVarint(out, 3, r.Count)
+}
+func (s *Service) seasonRewards(ctx command.Context, v *state, req []byte) ([]byte, error) {
+ if n(req, 2) != s.design.PackID {
+ return nil, fmt.Errorf("castle: invalid reward pack")
+ }
+ if s.settled == nil || s.grant == nil {
+ return nil, fmt.Errorf("castle: season settlement unavailable")
+ }
+ seasons, e := s.seasonFloors(ctx, v)
+ if e != nil {
+ return nil, e
+ }
+ ids := make([]uint64, 0, len(seasons))
+ for id := range seasons {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ for _, season := range ids {
+ if !s.settled(season) {
+ continue
+ }
+ key := fmt.Sprint(season)
+ _, claimed, e := ctx.State.LoadEntry("missions", "castle_season_claims", key)
+ if e != nil {
+ return nil, e
+ }
+ if claimed {
+ continue
+ }
+ records := recordsFor(season, seasons[season])
+ if len(records) == 0 {
+ continue
+ }
+ slices.SortFunc(records, func(a, b RankRecord) int { return cmp(a.Stage, b.Stage) })
+ var out []byte
+ var rewards []gamedata.Reward
+ for _, record := range records {
+ entry, e := s.placed(record)
+ if e != nil {
+ return nil, e
+ }
+ rows := s.design.FloorRanks
+ if record.Stage == 0 {
+ rows = s.design.TotalRanks
+ }
+ rs := castleRankRewards(rows, entry.Rank)
+ rewards = append(rewards, rs...)
+ row := wire.AppendVarint(nil, 1, entry.Rank)
+ if record.Stage == 0 {
+ row = wire.AppendVarint(row, 2, record.Point)
+ row = wire.AppendVarint(row, 3, 1)
+ for _, r := range rs {
+ row = wire.AppendBytes(row, 4, rewardWire(r))
+ }
+ out = wire.AppendBytes(out, 2, row)
+ } else {
+ row = wire.AppendVarint(row, 2, record.Stage)
+ row = wire.AppendVarint(row, 3, record.Point)
+ row = wire.AppendVarint(row, 4, 1)
+ for _, r := range rs {
+ row = wire.AppendBytes(row, 5, rewardWire(r))
+ }
+ out = wire.AppendBytes(out, 1, row)
+ }
+ }
+ bundle, e := s.grant(ctx, "castle:season:"+key, rewards)
+ if e != nil {
+ return nil, e
+ }
+ out = wire.AppendBytes(out, 3, bundle)
+ if e = ctx.State.PutEntry("missions", "castle_season_claims", key, []byte("true")); e != nil {
+ return nil, e
+ }
+ return out, nil
+ }
+ return wire.AppendBytes(nil, 3, nil), nil
+}
diff --git a/go/internal/server/domain/battle/castle/service.go b/go/internal/server/domain/battle/castle/service.go
new file mode 100644
index 0000000..1b271ac
--- /dev/null
+++ b/go/internal/server/domain/battle/castle/service.go
@@ -0,0 +1,467 @@
+package castle
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/battle"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+ "bytes"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "maps"
+ "math"
+ "slices"
+ "sort"
+ "time"
+)
+
+type Participant struct{ CharacterIndex, CostumeIndex, CharacterID, CostumeID uint64 }
+type Service struct {
+ rankOwner uint64
+ rankSource RankSource
+ settled func(uint64) bool
+ design *gamedata.CastleRewardDesign
+ now func() time.Time
+ period func(command.Context) (uint64, bool, error)
+ evidence func(command.Context) battle.SettlementEvidence
+ validate func(command.Context, []Participant) error
+ grant func(command.Context, string, []gamedata.Reward) ([]byte, error)
+ currentPack func(command.Context) (int, error)
+ characters *roster.CharacterStore
+ collection *roster.CollectionStore
+ equipment *assets.EquipmentInventory
+ wallet *assets.Wallet
+ totalWarCompletion func(command.Context, string, uint64, []uint64) error
+ totalWarTextCheck func(command.Context, string, string) error
+}
+
+func NewService(d *gamedata.CastleRewardDesign) *Service { return &Service{design: d, now: time.Now} }
+func (s *Service) AttachClock(f func() time.Time) { s.now = f }
+func (s *Service) AttachPeriod(f func(command.Context) (uint64, bool, error)) { s.period = f }
+func (s *Service) AttachEvidence(f func(command.Context) battle.SettlementEvidence) { s.evidence = f }
+func (s *Service) AttachTotalWarValidation(f func(command.Context, []Participant) error) {
+ s.validate = f
+}
+func (s *Service) AttachRewards(f func(command.Context, string, []gamedata.Reward) ([]byte, error)) {
+ s.grant = f
+}
+func (s *Service) AttachCurrentPack(f func(command.Context) (int, error)) { s.currentPack = f }
+
+type tower struct {
+ ID, Mode uint64
+ Challenges []uint64
+}
+type floor struct {
+ ID, Highest, Point, Retry, Achieved uint64
+ Rewarded bool
+}
+type run struct {
+ Floor, Retry uint64
+ Cleared map[uint64]bool
+ Point uint64
+}
+type encounter struct {
+ Mode, ID, Deck, Monster, Season uint64
+ Receipt string
+}
+type totalWarRun struct {
+ Identity string
+ Costumes []uint64
+ Request []byte
+}
+type score struct{ ID, Value uint64 }
+type state struct {
+ Season uint64
+ Towers map[string]tower
+ Floors map[uint64]floor
+ Run *run
+ Encounter *encounter
+ CastleClaimDay, TotalWarClaimDay string
+ TotalWarScores []score
+ TotalWarRun *totalWarRun
+ TotalWarDeck *totalWarDeckState
+}
+type receipt struct {
+ Digest [32]byte
+ Body []byte
+}
+
+func (s *Service) load(ctx command.Context) (*state, uint64, bool, error) {
+ if ctx.State == nil || s.design == nil || s.now == nil {
+ return nil, 0, false, fmt.Errorf("castle: storage/design unavailable")
+ }
+ v := &state{Towers: map[string]tower{}, Floors: map[uint64]floor{}}
+ raw, ok, e := ctx.State.LoadEntry("missions", "castle_state", "progress")
+ if e != nil {
+ return nil, 0, false, e
+ }
+ if ok && json.Unmarshal(raw, v) != nil {
+ return nil, 0, false, fmt.Errorf("castle: invalid saved progress")
+ }
+ if v.Towers == nil || v.Floors == nil {
+ return nil, 0, false, fmt.Errorf("castle: invalid progress maps")
+ }
+ var season uint64
+ active := false
+ if s.period != nil {
+ season, active, e = s.period(ctx)
+ if e != nil {
+ return nil, 0, false, e
+ }
+ }
+ if season != v.Season {
+ if v.Season != 0 && len(v.Floors) != 0 {
+ raw, err := json.Marshal(v.Floors)
+ if err != nil {
+ return nil, 0, false, err
+ }
+ if err = ctx.State.PutEntry("missions", "castle_seasons", fmt.Sprint(v.Season), raw); err != nil {
+ return nil, 0, false, err
+ }
+ }
+ v.Season = season
+ v.Floors = map[uint64]floor{}
+ v.Run = nil
+ if v.Encounter != nil && v.Encounter.Mode == 7 {
+ v.Encounter = nil
+ }
+ }
+ return v, season, active, nil
+}
+func save(ctx command.Context, v *state) error {
+ raw, e := json.Marshal(v)
+ if e != nil {
+ return e
+ }
+ return ctx.State.PutEntry("missions", "castle_state", "progress", raw)
+}
+func (s *Service) day() (string, error) { return s.design.Reset.Period(0, s.now()) }
+func n(raw []byte, num int) uint64 { v, _, _ := wire.Varint(raw, num); return v }
+func msgs(raw []byte, num int) ([][]byte, error) {
+ var out [][]byte
+ e := wire.Walk(raw, func(f wire.Field) error {
+ if f.Number == num {
+ if f.Type != 2 {
+ return wire.ErrMalformed
+ }
+ out = append(out, bytes.Clone(f.Value))
+ }
+ return nil
+ })
+ return out, e
+}
+func sum(v []score) uint64 {
+ var out uint64
+ for _, s := range v {
+ out += s.Value
+ }
+ return out
+}
+func castleTotal(v *state) uint64 {
+ var out uint64
+ for _, f := range v.Floors {
+ out += f.Highest
+ }
+ return out
+}
+func threshold(rows []gamedata.ScoreReward, value uint64) (gamedata.ScoreReward, bool) {
+ var out gamedata.ScoreReward
+ for _, r := range rows {
+ if float64(value) >= r.Score {
+ out = r
+ }
+ }
+ return out, out.ID != 0
+}
+func towerKey(mode, id uint64) string { return fmt.Sprintf("%d:%d", mode, id) }
+func towerWire(t tower) []byte {
+ out := wire.AppendVarint(nil, 1, t.ID)
+ for _, c := range t.Challenges {
+ out = wire.AppendVarint(out, 2, c)
+ }
+ return wire.AppendVarint(out, 3, t.Mode)
+}
+func floorWire(f floor) []byte {
+ out := wire.AppendVarint(nil, 2, f.ID)
+ out = wire.AppendVarint(out, 3, f.Retry)
+ out = wire.AppendVarint(out, 4, f.Point)
+ out = wire.AppendVarint(out, 5, f.Highest)
+ if f.Rewarded {
+ out = wire.AppendVarint(out, 6, 1)
+ }
+ return out
+}
+func totalWire(v *state) []byte { return wire.AppendVarint(nil, 2, castleTotal(v)) }
+func scoresWire(v []score) []byte {
+ var out []byte
+ for _, s := range v {
+ item := wire.AppendVarint(nil, 1, s.ID)
+ item = wire.AppendVarint(item, 2, s.Value)
+ out = wire.AppendBytes(out, 1, item)
+ }
+ return out
+}
+
+func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []byte, bool, error) {
+ codes := map[string]int{"/EvilCastleRankingInfo": 0, "/EvilCastleStageRankingInfo": 116, "/EvilCastleRewardInfo": 135, "/EvilCastleTowerInfo": 200, "/EvilCastleDailyRewardState": 441, "/EvilCastleDailyReward": 440, "/EvilCastleInfo": 112, "/EvilCastleEnter": 113, "/EvilCastlePing": 125, "/EvilCastleGiveUp": 547, "/EvilCastleStageClearReward": 115, "/TotalWarInfo": 236, "/TotalWarBattleStart": 243, "/TotalWarBattleEnd": 244, "/TotalWarRewardState": 252, "/TotalWarReward": 242}
+ maps.Copy(codes, totalWarDeckCodes)
+ code, handled := codes[path]
+ if !handled {
+ return 0, nil, false, nil
+ }
+ if _, totalWarDeckRequest := totalWarDeckCodes[path]; totalWarDeckRequest {
+ if _, err := totalWarScalar(req, 1); err != nil {
+ return code, nil, true, err
+ }
+ }
+ if len(req) > 4<<20 || n(req, 1) == 0 || n(req, 1) > math.MaxInt32 {
+ return code, nil, true, fmt.Errorf("castle: invalid request sequence/size")
+ }
+ if e := wire.Walk(req, func(wire.Field) error { return nil }); e != nil {
+ return code, nil, true, e
+ }
+ v, season, active, e := s.load(ctx)
+ if e != nil {
+ return code, nil, true, e
+ }
+ day, e := s.day()
+ if e != nil {
+ return code, nil, true, e
+ }
+ mutation := path != "/EvilCastleRankingInfo" && path != "/EvilCastleStageRankingInfo" && path != "/EvilCastleTowerInfo" && path != "/EvilCastleDailyRewardState" && path != "/TotalWarRewardState" && path != "/EvilCastleInfo" && path != "/TotalWarInfo" && path != "/EvilCastlePing" && path != "/TotalWarDeckInfo" && path != "/TotalWarDeckPresetInfo"
+ receiptKey := fmt.Sprintf("command:%s:%s:%d", ctx.SessionID, path, n(req, 1))
+ if mutation {
+ if out, ok, e := loadReceipt(ctx, receiptKey, req); e != nil || ok {
+ return code, out, true, e
+ }
+ }
+ var out []byte
+ switch path {
+ case "/EvilCastleRankingInfo", "/EvilCastleStageRankingInfo":
+ out, e = s.rankInfo(ctx, v, path, req)
+ if e != nil {
+ return code, nil, true, e
+ }
+ case "/EvilCastleRewardInfo":
+ out, e = s.seasonRewards(ctx, v, req)
+ if e != nil {
+ return code, nil, true, e
+ }
+ case "/EvilCastleTowerInfo":
+ keys := make([]string, 0, len(v.Towers))
+ for k := range v.Towers {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ out = wire.AppendBytes(out, 1, towerWire(v.Towers[k]))
+ }
+ case "/EvilCastleInfo":
+ ids := make([]uint64, 0, len(v.Floors))
+ for id := range v.Floors {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ for _, id := range ids {
+ out = wire.AppendBytes(out, 1, floorWire(v.Floors[id]))
+ }
+ out = wire.AppendBytes(out, 2, totalWire(v))
+ out = wire.AppendVarint(out, 3, season)
+ case "/EvilCastleDailyRewardState", "/TotalWarRewardState":
+ var available bool
+ if path == "/EvilCastleDailyRewardState" {
+ _, ok := threshold(s.design.Daily, castleTotal(v))
+ available = ok && active && v.CastleClaimDay != day
+ } else {
+ _, ok := threshold(s.design.TotalWarDaily, sum(v.TotalWarScores))
+ available = ok && v.TotalWarClaimDay != day
+ }
+ if available {
+ out = wire.AppendVarint(nil, 1, 1)
+ }
+ case "/EvilCastleDailyReward", "/TotalWarReward":
+ rows, points, claimed := s.design.Daily, castleTotal(v), v.CastleClaimDay
+ if path == "/TotalWarReward" {
+ rows, points, claimed = s.design.TotalWarDaily, sum(v.TotalWarScores), v.TotalWarClaimDay
+ }
+ r, ok := threshold(rows, points)
+ if !ok || claimed == day || (path == "/EvilCastleDailyReward" && !active) {
+ return code, nil, true, fmt.Errorf("castle: daily reward unavailable")
+ }
+ if s.grant == nil {
+ return code, nil, true, fmt.Errorf("castle: reward grant unavailable")
+ }
+ bundle, e := s.grant(ctx, "castle:daily:"+path+":"+day, []gamedata.Reward{r.Reward})
+ if e != nil {
+ return code, nil, true, e
+ }
+ out = wire.AppendBytes(nil, 1, bundle)
+ if path == "/TotalWarReward" {
+ v.TotalWarClaimDay = day
+ } else {
+ v.CastleClaimDay = day
+ }
+ case "/EvilCastleEnter":
+ if n(req, 2) != s.design.PackID {
+ return code, nil, true, fmt.Errorf("castle: castle season/pack unavailable")
+ }
+ if s.currentPack == nil {
+ return code, nil, true, fmt.Errorf("castle: current pack unavailable")
+ }
+ pack, e := s.currentPack(ctx)
+ if e != nil {
+ return code, nil, true, e
+ }
+ if uint64(pack) != s.design.PackID {
+ return code, nil, true, fmt.Errorf("castle: not in castle pack")
+ }
+ id := n(req, 3)
+ if id == 0 {
+ v.Run = nil
+ v.Encounter = nil
+ break
+ }
+ if !active {
+ return code, nil, true, fmt.Errorf("castle: castle season unavailable")
+ }
+ f, ok := s.design.Floors[id]
+ if !ok || (f.Previous != 0 && v.Floors[f.Previous].Highest == 0) {
+ return code, nil, true, fmt.Errorf("castle: floor locked")
+ }
+ if n(req, 4) != 0 || v.Run == nil || v.Run.Floor != id {
+ retry := uint64(0)
+ if v.Run != nil && v.Run.Floor == id {
+ retry = v.Run.Retry + 1
+ }
+ v.Run = &run{Floor: id, Retry: retry, Cleared: map[uint64]bool{}}
+ }
+ for monster, deck := range f.Monsters {
+ if v.Run.Cleared[monster] {
+ continue
+ }
+ item := wire.AppendVarint(nil, 1, monster)
+ item = wire.AppendVarint(item, 2, deck)
+ item = wire.AppendVarint(item, 6, 1)
+ out = wire.AppendBytes(out, 1, item)
+ }
+ case "/EvilCastlePing":
+ if v.Run == nil || v.Run.Floor != n(req, 2) {
+ return code, nil, true, fmt.Errorf("castle: no active floor")
+ }
+ out = wire.AppendVarint(nil, 1, v.Run.Point)
+ case "/EvilCastleGiveUp":
+ v.Run = nil
+ v.Encounter = nil
+ case "/EvilCastleStageClearReward":
+ if n(req, 2) != s.design.PackID {
+ return code, nil, true, fmt.Errorf("castle: invalid reward pack")
+ }
+ out, e = s.floorRewards(ctx, v, n(req, 3))
+ if e != nil {
+ return code, nil, true, e
+ }
+ case "/TotalWarContentsItemRenew", "/TotalWarDeckInfo", "/TotalWarDeckPresetInfo", "/TotalWarDeckPresetSave", "/TotalWarDeckPresetSlotAdd", "/TotalWarDeckSave", "/TotalWarEquipSave", "/TotalWarPresetDelete", "/TotalWarPresetInfoChange":
+ out, e = s.totalWarDeckHandle(ctx, v, path, req)
+ if e != nil {
+ return code, nil, true, e
+ }
+ case "/TotalWarInfo":
+ out = scoresWire(v.TotalWarScores)
+ case "/TotalWarBattleStart":
+ out, e = s.totalWarStart(ctx, v, req)
+ if e != nil {
+ return code, nil, true, e
+ }
+ case "/TotalWarBattleEnd":
+ out, e = s.totalWarEnd(ctx, v, req)
+ if e != nil {
+ return code, nil, true, e
+ }
+ }
+ raw, e := json.Marshal(v)
+ if e != nil {
+ return code, nil, true, e
+ }
+ changes := []stateio.EntryMutation{{Bucket: "castle_state", Key: "progress", Payload: raw}}
+ if mutation {
+ raw, e = json.Marshal(receipt{sha256.Sum256(req), out})
+ if e != nil {
+ return code, nil, true, e
+ }
+ changes = append(changes, stateio.EntryMutation{Bucket: "castle_receipts", Key: receiptKey, Payload: raw})
+ }
+ if e = ctx.State.SaveWithEntries("missions", nil, changes); e != nil {
+ return code, nil, true, e
+ }
+ return code, out, true, nil
+}
+
+func (s *Service) floorRewards(ctx command.Context, v *state, id uint64) ([]byte, error) {
+ if s.grant == nil {
+ return nil, fmt.Errorf("castle: reward grant unavailable")
+ }
+ var out []byte
+ granted := false
+ ids := []uint64{id}
+ if id == 0 {
+ ids = nil
+ for floor := range v.Floors {
+ ids = append(ids, floor)
+ }
+ slices.Sort(ids)
+ }
+ for _, id := range ids {
+ f, ok := v.Floors[id]
+ d, defined := s.design.Floors[id]
+ if !ok || !defined || f.Highest == 0 || f.Rewarded {
+ if len(ids) == 1 {
+ return nil, fmt.Errorf("castle: floor reward unavailable")
+ }
+ continue
+ }
+ bundle, e := s.grant(ctx, fmt.Sprintf("castle:floor:%d:%d", v.Season, id), d.Rewards)
+ if e != nil {
+ return nil, e
+ }
+ e = wire.Walk(bundle, func(field wire.Field) error {
+ to := map[int]int{1: 1, 2: 2, 3: 4, 4: 3}[field.Number]
+ if to != 0 {
+ out = wire.AppendBytes(out, to, field.Value)
+ }
+ return nil
+ })
+ if e != nil {
+ return nil, e
+ }
+ f.Rewarded = true
+ v.Floors[id] = f
+ granted = true
+ }
+ if !granted {
+ return nil, fmt.Errorf("castle: no floor rewards available")
+ }
+ return out, nil
+}
+
+func loadReceipt(ctx command.Context, key string, req []byte) ([]byte, bool, error) {
+ raw, ok, e := ctx.State.LoadEntry("missions", "castle_receipts", key)
+ if e != nil || !ok {
+ return nil, false, e
+ }
+ var r receipt
+ if json.Unmarshal(raw, &r) != nil || r.Digest != sha256.Sum256(req) {
+ return nil, false, fmt.Errorf("castle: changed settlement retry")
+ }
+ return r.Body, true, nil
+}
+func putReceipt(ctx command.Context, key string, req, body []byte) error {
+ raw, e := json.Marshal(receipt{sha256.Sum256(req), body})
+ if e != nil {
+ return e
+ }
+ return ctx.State.PutEntry("missions", "castle_receipts", key, raw)
+}
diff --git a/go/internal/server/domain/battle/castle/totalwar.go b/go/internal/server/domain/battle/castle/totalwar.go
new file mode 100644
index 0000000..a12f98e
--- /dev/null
+++ b/go/internal/server/domain/battle/castle/totalwar.go
@@ -0,0 +1,212 @@
+package castle
+
+import (
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "encoding/binary"
+ "fmt"
+ "math"
+ "slices"
+)
+
+func (s *Service) totalWarStart(ctx command.Context, v *state, req []byte) ([]byte, error) {
+ if n(req, 2) != 1 || s.validate == nil {
+ return nil, fmt.Errorf("castle: total war battle/ownership validation unavailable")
+ }
+ blue, e := msgs(req, 3)
+ if e != nil {
+ return nil, e
+ }
+ red, e := msgs(req, 4)
+ if e != nil {
+ return nil, e
+ }
+ if len(blue) == 0 || len(blue) > 2000 || len(red) == 0 || len(red) > 20 {
+ return nil, fmt.Errorf("castle: invalid total war teams")
+ }
+ if s.characters != nil {
+ if e = s.validateSavedTotalWarBattle(ctx, v, blue); e != nil {
+ return nil, e
+ }
+ }
+ participants := make([]Participant, 0, len(blue))
+ seen := map[uint64]bool{}
+ unique := map[uint64]bool{}
+ var costumes []uint64
+ for _, raw := range blue {
+ p := Participant{n(raw, 2), n(raw, 6), n(raw, 3), n(raw, 7)}
+ attacker := n(raw, 28) == 0
+ if p.CharacterIndex == 0 || p.CostumeIndex == 0 || p.CharacterID == 0 || p.CostumeID == 0 || seen[p.CostumeID] || n(raw, 28) > 1 || attacker && (n(raw, 1) == 0 || unique[n(raw, 1)]) || !attacker && n(raw, 1) != 0 {
+ return nil, fmt.Errorf("castle: invalid total war participant")
+ }
+ seen[p.CostumeID] = true
+ if attacker {
+ unique[n(raw, 1)] = true
+ }
+ participants = append(participants, p)
+ if attacker {
+ costumes = append(costumes, p.CostumeID)
+ }
+ }
+ if len(costumes) == 0 || len(costumes) > 20 {
+ return nil, fmt.Errorf("castle: invalid total war attacker count")
+ }
+ if len(red) != len(s.design.TotalWarEnemies) || len(red) == 0 {
+ return nil, fmt.Errorf("castle: total war enemies differ from design")
+ }
+ for i, raw := range red {
+ enemy := s.design.TotalWarEnemies[i]
+ index := n(raw, 1)
+ if index == 0 || unique[index] || n(raw, 2) != 0 || n(raw, 3) != enemy.ID || n(raw, 4) != 1000000 || n(raw, 5) != enemy.Level || n(raw, 9) != uint64(i) || n(raw, 7) != 0 {
+ return nil, fmt.Errorf("castle: invalid total war enemy")
+ }
+ unique[index] = true
+ }
+ if e = s.validate(ctx, participants); e != nil {
+ return nil, e
+ }
+ v.TotalWarRun = &totalWarRun{Identity: fmt.Sprintf("%s:%d", ctx.SessionID, n(req, 1)), Costumes: costumes, Request: req}
+ // Engine V1 runs the client simulation and consumes the registered costume
+ // damage report. No verified combat result is fabricated by this service.
+ out := wire.AppendVarint(nil, 1, n(req, 1)*7919%math.MaxInt32+1)
+ for _, raw := range blue {
+ out = wire.AppendBytes(out, 2, raw)
+ }
+ for _, raw := range red {
+ out = wire.AppendBytes(out, 3, raw)
+ }
+ return out, nil
+}
+
+func (s *Service) totalWarEnd(ctx command.Context, v *state, req []byte) ([]byte, error) {
+ if v.TotalWarRun == nil {
+ return nil, fmt.Errorf("castle: total war settlement without start")
+ }
+ items, e := msgs(req, 2)
+ if e != nil {
+ return nil, e
+ }
+ if len(items) > len(v.TotalWarRun.Costumes) {
+ return nil, fmt.Errorf("castle: excess total war scores")
+ }
+ var scores []score
+ seen := map[uint64]bool{}
+ var total uint64
+ for _, raw := range items {
+ id, damage := n(raw, 1), n(raw, 2)
+ if !slices.Contains(v.TotalWarRun.Costumes, id) || seen[id] || damage > math.MaxInt64 || total > math.MaxInt64-damage {
+ return nil, fmt.Errorf("castle: invalid total war score")
+ }
+ seen[id] = true
+ total += damage
+ scores = append(scores, score{id, damage})
+ }
+ if len(items) != 0 && len(items) != len(v.TotalWarRun.Costumes) {
+ return nil, fmt.Errorf("castle: missing total war attacker score")
+ }
+ if len(scores) > 0 && (len(v.TotalWarScores) == 0 || total > sum(v.TotalWarScores)) {
+ if s.totalWarCompletion != nil {
+ if e = s.totalWarCompletion(ctx, v.TotalWarRun.Identity, total, v.TotalWarRun.Costumes); e != nil {
+ return nil, e
+ }
+ }
+ v.TotalWarScores = scores
+ }
+ v.TotalWarRun = nil
+ return scoresWire(v.TotalWarScores), nil
+}
+
+func (s *Service) validateSavedTotalWarBattle(ctx command.Context, v *state, blue [][]byte) error {
+ if v.TotalWarDeck == nil || len(v.TotalWarDeck.Deck) == 0 {
+ return fmt.Errorf("castle: total war formation not saved")
+ }
+ d := v.TotalWarDeck
+ if e := s.validateTotalWarDeck(ctx, d.Deck); e != nil {
+ return e
+ }
+ if e := s.validateTotalWarContents(ctx, d.Contents); e != nil {
+ return e
+ }
+ if len(blue) != len(d.Deck) {
+ return fmt.Errorf("castle: battle costumes differ from saved formation")
+ }
+ // The client emits attackers in formation order, then cheering costumes.
+ ordered := make([][]byte, 0, len(d.Deck))
+ for _, mode := range []uint64{0, 1} {
+ for _, entry := range d.Deck {
+ if n(entry, 1) == mode {
+ ordered = append(ordered, entry)
+ }
+ }
+ }
+ contents := map[uint64][]byte{}
+ for _, entry := range d.Contents {
+ contents[n(entry, 1)] = entry
+ }
+ for i, raw := range blue {
+ deck := ordered[i]
+ index := n(deck, 3)
+ if n(raw, 2) != index || n(raw, 6) != n(deck, 2) || n(raw, 28) != n(deck, 1) {
+ return fmt.Errorf("castle: battle costume role or order differs from saved formation")
+ }
+ content := contents[index]
+ if content == nil || n(raw, 29) != n(content, 3) {
+ return fmt.Errorf("castle: battle potential differs from saved formation")
+ }
+ refs, e := msgs(content, 2)
+ if e != nil {
+ return e
+ }
+ want := map[uint64]bool{}
+ for _, ref := range refs {
+ if id := n(ref, 1); id != 0 {
+ want[id] = true
+ }
+ }
+ got := map[uint64]bool{}
+ e = wire.Walk(raw, func(f wire.Field) error {
+ if f.Number != 12 {
+ return nil
+ }
+ consume := func(id uint64) error {
+ if id == 0 || got[id] || !want[id] {
+ return fmt.Errorf("castle: battle equipment differs from saved formation")
+ }
+ got[id] = true
+ return nil
+ }
+ if f.Type == 0 {
+ id, k := binary.Uvarint(f.Value)
+ if k <= 0 {
+ return wire.ErrMalformed
+ }
+ return consume(id)
+ }
+ if f.Type != 2 {
+ return wire.ErrMalformed
+ }
+ for p := f.Value; len(p) > 0; {
+ id, k := binary.Uvarint(p)
+ if k <= 0 {
+ return wire.ErrMalformed
+ }
+ if e := consume(id); e != nil {
+ return e
+ }
+ p = p[k:]
+ }
+ return nil
+ })
+ if e != nil {
+ return e
+ }
+ if len(want) != len(got) {
+ return fmt.Errorf("castle: battle equipment missing from saved formation")
+ }
+ }
+ return nil
+}
+
+func (s *Service) AttachTotalWarCompletion(f func(command.Context, string, uint64, []uint64) error) {
+ s.totalWarCompletion = f
+}
diff --git a/go/internal/server/domain/battle/castle/totalwar_deck.go b/go/internal/server/domain/battle/castle/totalwar_deck.go
new file mode 100644
index 0000000..10125d6
--- /dev/null
+++ b/go/internal/server/domain/battle/castle/totalwar_deck.go
@@ -0,0 +1,497 @@
+package castle
+
+import (
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+ "encoding/binary"
+ "fmt"
+ "math"
+ "slices"
+ "unicode"
+ "unicode/utf8"
+)
+
+var totalWarDeckCodes = map[string]int{"/TotalWarContentsItemRenew": 402, "/TotalWarDeckInfo": 237, "/TotalWarDeckPresetInfo": 239, "/TotalWarDeckPresetSave": 240, "/TotalWarDeckPresetSlotAdd": 241, "/TotalWarDeckSave": 238, "/TotalWarEquipSave": 0, "/TotalWarPresetDelete": 0, "/TotalWarPresetInfoChange": 0}
+
+type totalWarDeckState struct {
+ Slots uint64
+ Deck, Contents [][]byte
+ Presets map[uint64][]byte
+}
+
+func (s *Service) AttachTotalWarRuntime(c *roster.CharacterStore, col *roster.CollectionStore, e *assets.EquipmentInventory, w *assets.Wallet) error {
+ if c == nil || col == nil || e == nil || w == nil {
+ return fmt.Errorf("castle: incomplete total war runtime")
+ }
+ s.characters, s.collection, s.equipment, s.wallet = c, col, e, w
+ return nil
+}
+func (s *Service) TotalWarPresetSlotCount(ctx command.Context) (uint64, error) {
+ v, _, _, e := s.load(ctx)
+ if e != nil {
+ return 0, e
+ }
+ d, e := s.totalWarDeckState(v)
+ if e != nil {
+ return 0, e
+ }
+ return d.Slots, nil
+}
+func (s *Service) totalWarDeckState(v *state) (*totalWarDeckState, error) {
+ r := s.design.TotalWarPresets
+ if r == nil {
+ return nil, fmt.Errorf("castle: total war preset design unavailable")
+ }
+ if v.TotalWarDeck == nil {
+ v.TotalWarDeck = &totalWarDeckState{Slots: r.BaseCount, Presets: map[uint64][]byte{}}
+ }
+ d := v.TotalWarDeck
+ if d.Presets == nil || d.Slots < r.BaseCount || d.Slots > r.Maximum {
+ return nil, fmt.Errorf("castle: invalid total war slots")
+ }
+ return d, nil
+}
+func totalWarScalar(raw []byte, field int) (uint64, error) {
+ var value uint64
+ found := false
+ err := wire.Walk(raw, func(f wire.Field) error {
+ if f.Number != field {
+ return nil
+ }
+ if f.Type != 0 || found {
+ return fmt.Errorf("castle: invalid total war scalar %d", field)
+ }
+ found = true
+ value, _ = binary.Uvarint(f.Value)
+ if value > math.MaxInt64 {
+ return fmt.Errorf("castle: invalid total war scalar %d", field)
+ }
+ return nil
+ })
+ return value, err
+}
+func (s *Service) validateTotalWarDeck(ctx command.Context, deck [][]byte) error {
+ if s.characters == nil || s.collection == nil {
+ return fmt.Errorf("castle: total war ownership unavailable")
+ }
+ if len(deck) > len(s.collection.Costumes()) {
+ return fmt.Errorf("castle: excess total war costumes")
+ }
+ seen := map[uint64]bool{}
+ attackers := 0
+ for _, raw := range deck {
+ mode, e := totalWarScalar(raw, 1)
+ if e != nil || mode > 1 {
+ return fmt.Errorf("castle: invalid total war role")
+ }
+ costume, e := totalWarScalar(raw, 2)
+ if e != nil {
+ return e
+ }
+ index, e := totalWarScalar(raw, 3)
+ if e != nil {
+ return e
+ }
+ c, ok := s.characters.Find(ctx, index)
+ if !ok || roster.IsStoryCharacter(c) || roster.IsCharmCharacter(c) || roster.CharacterExpired(c, s.now()) {
+ return fmt.Errorf("castle: total war character not permanently owned")
+ }
+ owned, ok := s.collection.CostumeByIndex(costume)
+ if !ok || owned.UseChar != index || seen[costume] {
+ return fmt.Errorf("castle: total war costume not owned or repeated")
+ }
+ seen[costume] = true
+ if mode == 0 {
+ attackers++
+ }
+ }
+ if attackers > 20 {
+ return fmt.Errorf("castle: more than twenty total war attackers")
+ }
+ return nil
+}
+func (s *Service) validateTotalWarContents(ctx command.Context, contents [][]byte) error {
+ if s.characters == nil || s.collection == nil || s.equipment == nil {
+ return fmt.Errorf("castle: total war equipment runtime unavailable")
+ }
+ var bindings []assets.PresetEquipmentBinding
+ seen := map[uint64]bool{}
+ for _, raw := range contents {
+ index, e := totalWarScalar(raw, 1)
+ if e != nil || index == 0 || seen[index] {
+ return fmt.Errorf("castle: duplicate or invalid total war equipment character")
+ }
+ seen[index] = true
+ c, ok := s.characters.Find(ctx, index)
+ if !ok || roster.IsStoryCharacter(c) || roster.IsCharmCharacter(c) || roster.CharacterExpired(c, s.now()) {
+ return fmt.Errorf("castle: equipment character not permanently owned")
+ }
+ connect, e := totalWarScalar(raw, 3)
+ if e != nil || connect > math.MaxInt32 {
+ return fmt.Errorf("castle: invalid total war potential costume")
+ }
+ if connect != 0 && connect != c.ConnectPotentialCostume {
+ owned := false
+ for _, costume := range s.collection.Costumes() {
+ if costume.ID == connect && costume.UseChar == index {
+ owned = true
+ break
+ }
+ }
+ if !owned {
+ return fmt.Errorf("castle: total war potential costume not owned")
+ }
+ }
+ refs, e := msgs(raw, 2)
+ if e != nil {
+ return e
+ }
+ b := assets.PresetEquipmentBinding{CharacterIndex: index, Equipment: make([]uint64, 5)}
+ slots := map[uint64]bool{}
+ for _, ref := range refs {
+ slot, e := totalWarScalar(ref, 2)
+ if e != nil || slot >= 5 || slots[slot] {
+ return fmt.Errorf("castle: duplicate or invalid total war equipment slot")
+ }
+ slots[slot] = true
+ id, e := totalWarScalar(ref, 1)
+ if e != nil {
+ return e
+ }
+ b.Equipment[slot] = id
+ }
+ bindings = append(bindings, b)
+ }
+ if len(bindings) > 0 {
+ return s.equipment.ValidatePresetEquipment(ctx, bindings)
+ }
+ return nil
+}
+func (s *Service) totalWarLiveContents(ctx command.Context) ([][]byte, error) {
+ if s.characters == nil || s.equipment == nil {
+ return nil, fmt.Errorf("castle: total war live equipment unavailable")
+ }
+ equipment := map[uint64][]assets.Equipment{}
+ for _, item := range s.equipment.All(ctx) {
+ equipment[item.UseChar] = append(equipment[item.UseChar], item)
+ }
+ var out [][]byte
+ for _, c := range s.characters.All(ctx) {
+ if roster.IsStoryCharacter(c) || roster.IsCharmCharacter(c) || roster.CharacterExpired(c, s.now()) {
+ continue
+ }
+ raw := wire.AppendVarint(nil, 1, c.InvenIndex)
+ raw = wire.AppendVarint(raw, 3, c.ConnectPotentialCostume)
+ slots := make([]uint64, 5)
+ for _, item := range equipment[c.InvenIndex] {
+ slot, ok := s.equipment.EquipmentSlot(item.ID)
+ if !ok || slot >= 5 {
+ return nil, fmt.Errorf("castle: live equipment slot unavailable")
+ }
+ if slots[slot] != 0 {
+ return nil, fmt.Errorf("castle: live equipment occupies duplicate slot")
+ }
+ slots[slot] = item.InvenIndex
+ }
+ for slot, id := range slots {
+ ref := wire.AppendVarint(nil, 1, id)
+ ref = wire.AppendVarint(ref, 2, uint64(slot))
+ raw = wire.AppendBytes(raw, 2, ref)
+ }
+ out = append(out, raw)
+ }
+ return out, s.validateTotalWarContents(ctx, out)
+}
+func (s *Service) AttachTotalWarTextCheck(check func(command.Context, string, string) error) {
+ s.totalWarTextCheck = check
+}
+func (s *Service) validateTotalWarPreset(ctx command.Context, d *totalWarDeckState, raw []byte) error {
+ if err := s.validateTotalWarPresetShape(ctx, d, raw); err != nil {
+ return err
+ }
+ name, _, err := wire.Bytes(raw, 2)
+ if err != nil {
+ return err
+ }
+ if len(name) > 0 {
+ if s.totalWarTextCheck == nil {
+ return fmt.Errorf("castle: total war text approval unavailable")
+ }
+ return s.totalWarTextCheck(ctx, "total_war_preset_name", string(name))
+ }
+ return nil
+}
+func (s *Service) validateTotalWarPresetShape(ctx command.Context, d *totalWarDeckState, raw []byte) error {
+ slot, e := totalWarScalar(raw, 1)
+ if e != nil || slot >= d.Slots {
+ return fmt.Errorf("castle: unavailable total war preset slot")
+ }
+ name, _, e := wire.Bytes(raw, 2)
+ if e != nil || !utf8.Valid(name) || utf8.RuneCount(name) > 16 {
+ return fmt.Errorf("castle: invalid total war preset name")
+ }
+ for _, r := range string(name) {
+ if unicode.IsControl(r) || r == '<' || r == '>' {
+ return fmt.Errorf("castle: invalid total war preset name")
+ }
+ }
+ icon, e := totalWarScalar(raw, 3)
+ if e != nil || icon != 0 && !s.design.TotalWarPresets.Icons[icon] {
+ return fmt.Errorf("castle: invalid total war preset icon")
+ }
+ color, e := totalWarScalar(raw, 4)
+ if e != nil || color > 5 {
+ return fmt.Errorf("castle: invalid total war preset color")
+ }
+ deck, e := msgs(raw, 5)
+ if e != nil {
+ return e
+ }
+ return s.validateTotalWarDeck(ctx, deck)
+}
+func totalWarSlots(raw []byte) ([]uint64, error) {
+ var out []uint64
+ e := wire.Walk(raw, func(f wire.Field) error {
+ if f.Number != 2 {
+ return nil
+ }
+ if f.Type == 0 {
+ v, k := binary.Uvarint(f.Value)
+ if k <= 0 {
+ return wire.ErrMalformed
+ }
+ out = append(out, v)
+ return nil
+ }
+ if f.Type != 2 {
+ return wire.ErrMalformed
+ }
+ for p := f.Value; len(p) > 0; {
+ v, k := binary.Uvarint(p)
+ if k <= 0 {
+ return wire.ErrMalformed
+ }
+ out = append(out, v)
+ p = p[k:]
+ }
+ return nil
+ })
+ return out, e
+}
+func (s *Service) totalWarDeckHandle(ctx command.Context, v *state, path string, req []byte) ([]byte, error) {
+ d, e := s.totalWarDeckState(v)
+ if e != nil {
+ return nil, e
+ }
+ switch path {
+ case "/TotalWarDeckInfo":
+ if e = s.validateTotalWarDeck(ctx, d.Deck); e != nil {
+ return nil, e
+ }
+ var out []byte
+ for _, raw := range d.Deck {
+ out = wire.AppendBytes(out, 1, raw)
+ }
+ for _, raw := range d.Contents {
+ out = wire.AppendBytes(out, 2, raw)
+ }
+ return out, nil
+ case "/TotalWarDeckSave":
+ deck, e := msgs(req, 2)
+ if e != nil {
+ return nil, e
+ }
+ if len(deck) == 0 {
+ return nil, fmt.Errorf("castle: empty total war formation")
+ }
+ if e = s.validateTotalWarDeck(ctx, deck); e != nil {
+ return nil, e
+ }
+ requested, e := msgs(req, 3)
+ if e != nil {
+ return nil, e
+ }
+ if e = s.validateTotalWarContents(ctx, requested); e != nil {
+ return nil, e
+ }
+ contents := mergeTotalWarContents(d.Contents, requested)
+ live, e := s.totalWarLiveContents(ctx)
+ if e != nil {
+ return nil, e
+ }
+ present := map[uint64]bool{}
+ for _, raw := range contents {
+ present[n(raw, 1)] = true
+ }
+ for _, raw := range live {
+ if !present[n(raw, 1)] {
+ contents = append(contents, raw)
+ }
+ }
+ if e = s.validateTotalWarContents(ctx, contents); e != nil {
+ return nil, e
+ }
+ d.Deck, d.Contents = deck, contents
+ case "/TotalWarContentsItemRenew":
+ contents, e := s.totalWarLiveContents(ctx)
+ if e != nil {
+ return nil, e
+ }
+ d.Contents = contents
+ var out []byte
+ for _, raw := range contents {
+ out = wire.AppendBytes(out, 1, raw)
+ }
+ return out, nil
+ case "/TotalWarEquipSave":
+ requested, e := msgs(req, 2)
+ if e != nil {
+ return nil, e
+ }
+ if len(requested) == 0 {
+ return nil, fmt.Errorf("castle: empty total war equipment update")
+ }
+ for i, raw := range requested {
+ if e = wire.Walk(raw, func(f wire.Field) error {
+ if f.Number > 2 {
+ return fmt.Errorf("castle: invalid total war equipment field")
+ }
+ return nil
+ }); e != nil {
+ return nil, e
+ }
+ index := n(raw, 1)
+ for _, old := range d.Contents {
+ if n(old, 1) == index {
+ raw = wire.AppendVarint(raw, 3, n(old, 3))
+ break
+ }
+ }
+ requested[i] = raw
+ }
+ if e = s.validateTotalWarContents(ctx, requested); e != nil {
+ return nil, e
+ }
+ contents := mergeTotalWarContents(d.Contents, requested)
+ if e = s.validateTotalWarContents(ctx, contents); e != nil {
+ return nil, e
+ }
+ d.Contents = contents
+ case "/TotalWarDeckPresetInfo":
+ var out []byte
+ for slot := range d.Slots {
+ if raw := d.Presets[slot]; raw != nil {
+ if e = s.validateTotalWarPresetShape(ctx, d, raw); e != nil {
+ return nil, e
+ }
+ out = wire.AppendBytes(out, 1, raw)
+ }
+ }
+ return out, nil
+ case "/TotalWarDeckPresetSave":
+ raw, ok, e := wire.Bytes(req, 2)
+ if e != nil || !ok {
+ return nil, fmt.Errorf("castle: missing total war preset")
+ }
+ if e = s.validateTotalWarPreset(ctx, d, raw); e != nil {
+ return nil, e
+ }
+ d.Presets[n(raw, 1)] = raw
+ case "/TotalWarPresetInfoChange":
+ slot, e := totalWarScalar(req, 5)
+ if e != nil || slot >= d.Slots {
+ return nil, fmt.Errorf("castle: unavailable total war preset slot")
+ }
+ raw := wire.AppendVarint(nil, 1, slot)
+ name, _, e := wire.Bytes(req, 2)
+ if e != nil {
+ return nil, e
+ }
+ raw = wire.AppendBytes(raw, 2, name)
+ icon, e := totalWarScalar(req, 3)
+ if e != nil {
+ return nil, e
+ }
+ color, e := totalWarScalar(req, 4)
+ if e != nil {
+ return nil, e
+ }
+ raw = wire.AppendVarint(raw, 3, icon)
+ raw = wire.AppendVarint(raw, 4, color)
+ deck, e := msgs(d.Presets[slot], 5)
+ if e != nil {
+ return nil, e
+ }
+ for _, entry := range deck {
+ raw = wire.AppendBytes(raw, 5, entry)
+ }
+ if e = s.validateTotalWarPreset(ctx, d, raw); e != nil {
+ return nil, e
+ }
+ d.Presets[slot] = raw
+ case "/TotalWarPresetDelete":
+ slots, e := totalWarSlots(req)
+ if e != nil || len(slots) == 0 {
+ return nil, fmt.Errorf("castle: invalid total war preset deletion")
+ }
+ for _, slot := range slots {
+ if slot >= d.Slots {
+ return nil, fmt.Errorf("castle: unavailable total war preset slot")
+ }
+ }
+ for _, slot := range slots {
+ delete(d.Presets, slot)
+ }
+ case "/TotalWarDeckPresetSlotAdd":
+ count, e := totalWarScalar(req, 2)
+ r := s.design.TotalWarPresets
+ if e != nil || count == 0 || count > r.Maximum || d.Slots > r.Maximum-count || r.Price == 0 || count > math.MaxUint64/r.Price {
+ return nil, fmt.Errorf("castle: invalid total war slot purchase")
+ }
+ if s.wallet == nil {
+ return nil, fmt.Errorf("castle: total war wallet unavailable")
+ }
+ id := fmt.Sprintf("castle:totalwar:preset:%s:%s:%d", ctx.AccountID, ctx.SessionID, n(req, 1))
+ price := count * r.Price
+ switch r.PriceType {
+ case 2:
+ _, e = s.wallet.SpendJewelryOnce(ctx, id, price)
+ case 3:
+ _, e = s.wallet.SpendFreeJewelryOnce(ctx, id, price)
+ case 4:
+ _, e = s.wallet.SpendGoldOnce(ctx, id, price)
+ case 12:
+ _, e = s.wallet.SpendCatalystOnce(ctx, id, price)
+ default:
+ e = fmt.Errorf("castle: unsupported total war preset currency")
+ }
+ if e != nil {
+ return nil, e
+ }
+ d.Slots += count
+ default:
+ return nil, fmt.Errorf("castle: unknown total war deck operation")
+ }
+ return nil, nil
+}
+func mergeTotalWarContents(previous, requested [][]byte) [][]byte {
+ byIndex := map[uint64][]byte{}
+ for _, raw := range previous {
+ byIndex[n(raw, 1)] = raw
+ }
+ for _, raw := range requested {
+ byIndex[n(raw, 1)] = raw
+ }
+ indices := make([]uint64, 0, len(byIndex))
+ for id := range byIndex {
+ indices = append(indices, id)
+ }
+ slices.Sort(indices)
+ out := make([][]byte, 0, len(indices))
+ for _, id := range indices {
+ out = append(out, byIndex[id])
+ }
+ return out
+}
diff --git a/go/internal/server/domain/battle/castle/totalwar_deck_test.go b/go/internal/server/domain/battle/castle/totalwar_deck_test.go
new file mode 100644
index 0000000..a30f60c
--- /dev/null
+++ b/go/internal/server/domain/battle/castle/totalwar_deck_test.go
@@ -0,0 +1,793 @@
+package castle
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+ accountstate "bd2server/internal/server/storage/account"
+ "bd2server/internal/server/storage/stateio"
+ "bytes"
+ "context"
+ "fmt"
+ "path/filepath"
+ "testing"
+)
+
+type totalWarFixture struct {
+ repo *accountstate.Repository
+ design *gamedata.CastleRewardDesign
+ path string
+ costumes []roster.Costume
+ characters []roster.Character
+ completion func(command.Context, string, uint64, []uint64) error
+}
+type totalWarRuntime struct {
+ service *Service
+ wallet *assets.Wallet
+ equipment *assets.EquipmentInventory
+ characters *roster.CharacterStore
+ collection *roster.CollectionStore
+}
+
+func newTotalWarFixture(t *testing.T, characters ...roster.Character) *totalWarFixture {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "state.db")
+ r, e := accountstate.Open(path)
+ if e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() {
+ if e := r.Close(); e != nil {
+ t.Error(e)
+ }
+ })
+ d := testDesign()
+ d.TotalWarPresets = &gamedata.PresetDesign{BaseCount: 5, Maximum: 5, PriceType: 4, Price: 2000, Icons: map[uint64]bool{11: true}}
+ f := &totalWarFixture{repo: r, design: d, path: path, characters: characters}
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ if e := rt.wallet.EnsurePersisted(ctx); e != nil {
+ return e
+ }
+ if e := rt.characters.EnsurePersisted(ctx); e != nil {
+ return e
+ }
+ if e := rt.collection.EnsurePersisted(ctx); e != nil {
+ return e
+ }
+ weapon, e := rt.equipment.GrantOnce(ctx, "weapon", 700)
+ if e != nil {
+ return e
+ }
+ shield, e := rt.equipment.GrantOnce(ctx, "shield", 701)
+ if e != nil {
+ return e
+ }
+ _, e = rt.equipment.ApplyPresetEquipment(ctx, []assets.PresetEquipmentBinding{{CharacterIndex: 81, Equipment: []uint64{weapon.InvenIndex, 0, 0, 0, 0}}, {CharacterIndex: 82, Equipment: []uint64{0, shield.InvenIndex, 0, 0, 0}}})
+ return e
+ }, false)
+ return f
+}
+func (f *totalWarFixture) open(t *testing.T, ctx command.Context) totalWarRuntime {
+ t.Helper()
+ scope := stateio.RootStore{}
+ i, e := assets.OpenInventory(ctx, scope, nil)
+ if e != nil {
+ t.Fatal(e)
+ }
+ w, e := assets.OpenWallet(ctx, scope, assets.Currency{Gold: 10000})
+ if e != nil {
+ t.Fatal(e)
+ }
+ chars := []roster.Character{{InvenIndex: 81, ID: 71, Level: 1, ExpiryTime: ^uint64(0) - 32399999}, {InvenIndex: 82, ID: 72, Level: 1}}
+ if len(f.characters) > 0 {
+ chars = f.characters
+ }
+ costumes := []roster.Costume{{InvenIndex: 101, ID: 91, UseChar: 81}, {InvenIndex: 102, ID: 92, UseChar: 81}, {InvenIndex: 103, ID: 93, UseChar: 82}}
+ if f.costumes != nil {
+ costumes = f.costumes
+ }
+ col, e := roster.OpenCollectionStore(ctx, scope, costumes)
+ if e != nil {
+ t.Fatal(e)
+ }
+ c, e := roster.OpenCharacterStore(ctx, scope, chars, i, "", "")
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = c.AttachCollection(ctx, col); e != nil {
+ t.Fatal(e)
+ }
+ if e = col.BindBaseCharacters(ctx, chars); e != nil {
+ t.Fatal(e)
+ }
+ equipment, e := assets.OpenEquipmentInventory(ctx, scope)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = equipment.AttachCharacters(ctx, c); e != nil {
+ t.Fatal(e)
+ }
+ if e = equipment.AttachSlots(ctx, map[uint64]uint64{700: 0, 701: 1}); e != nil {
+ t.Fatal(e)
+ }
+ s := NewService(f.design)
+ if e = s.AttachTotalWarRuntime(c, col, equipment, w); e != nil {
+ t.Fatal(e)
+ }
+ s.AttachTotalWarValidation(func(_ command.Context, ps []Participant) error {
+ for _, p := range ps {
+ costume, ok := col.CostumeByIndex(p.CostumeIndex)
+ if !ok || costume.UseChar != p.CharacterIndex || costume.ID != p.CostumeID {
+ return fmt.Errorf("not owned")
+ }
+ }
+ return nil
+ })
+ s.AttachTotalWarTextCheck(func(command.Context, string, string) error { return nil })
+ s.AttachTotalWarCompletion(f.completion)
+ s.AttachRewards(func(ctx command.Context, id string, rewards []gamedata.Reward) ([]byte, error) {
+ _, e := w.GrantQuestOnce(ctx, id, rewards)
+ return nil, e
+ })
+ return totalWarRuntime{s, w, equipment, c, col}
+}
+func (f *totalWarFixture) command(t *testing.T, run func(command.Context, totalWarRuntime) error, wantError bool) {
+ t.Helper()
+ tx, e := f.repo.BeginCommand(context.Background())
+ if e != nil {
+ t.Fatal(e)
+ }
+ ctx := command.Context{Identity: command.Identity{AccountID: "total-war-account", SessionID: "login"}, State: tx}
+ rt := f.open(t, ctx)
+ e = run(ctx, rt)
+ if wantError {
+ if e == nil {
+ _ = tx.Rollback()
+ t.Fatal("invalid operation succeeded")
+ }
+ if e = tx.Rollback(); e != nil {
+ t.Fatal(e)
+ }
+ return
+ }
+ if e != nil {
+ _ = tx.Rollback()
+ t.Fatal(e)
+ }
+ if e = tx.Commit(); e != nil {
+ t.Fatal(e)
+ }
+}
+func totalWarDeckEntry(role, costume, char uint64) []byte {
+ raw := wire.AppendVarint(nil, 1, role)
+ raw = wire.AppendVarint(raw, 2, costume)
+ return wire.AppendVarint(raw, 3, char)
+}
+func totalWarDeckRequest(seq uint64, deck ...[]byte) []byte {
+ raw := request(seq)
+ for _, entry := range deck {
+ raw = wire.AppendBytes(raw, 2, entry)
+ }
+ return raw
+}
+func totalWarContent(char uint64, ids ...uint64) []byte {
+ raw := wire.AppendVarint(nil, 1, char)
+ for slot, id := range ids {
+ ref := wire.AppendVarint(nil, 1, id)
+ ref = wire.AppendVarint(ref, 2, uint64(slot))
+ raw = wire.AppendBytes(raw, 2, ref)
+ }
+ return raw
+}
+func totalWarEquipmentFor(t *testing.T, body []byte, field int, char, slot uint64) uint64 {
+ t.Helper()
+ contents, e := msgs(body, field)
+ if e != nil {
+ t.Fatal(e)
+ }
+ for _, raw := range contents {
+ if n(raw, 1) != char {
+ continue
+ }
+ refs, e := msgs(raw, 2)
+ if e != nil {
+ t.Fatal(e)
+ }
+ for _, ref := range refs {
+ if n(ref, 2) == slot {
+ return n(ref, 1)
+ }
+ }
+ }
+ t.Fatalf("missing character %d slot %d", char, slot)
+ return 0
+}
+func totalWarCall(ctx command.Context, rt totalWarRuntime, path string, req []byte) ([]byte, error) {
+ _, body, handled, e := rt.service.Handle(ctx, path, req)
+ if !handled {
+ return nil, fmt.Errorf("unhandled %s", path)
+ }
+ return body, e
+}
+
+func TestTotalWarIndependentEquipmentTransferRenewAndReopen(t *testing.T) {
+ f := newTotalWarFixture(t)
+ var weapon, shield uint64
+ deck := [][]byte{totalWarDeckEntry(0, 102, 81), totalWarDeckEntry(0, 101, 81), totalWarDeckEntry(1, 103, 82)}
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ var e error
+ empty, e := totalWarCall(ctx, rt, "/TotalWarDeckInfo", request(1))
+ if e != nil {
+ return e
+ }
+ if len(empty) != 0 {
+ t.Fatal("uninitialized formation should trigger client InitialSort")
+ }
+ for _, item := range rt.equipment.All(ctx) {
+ if item.ID == 700 {
+ weapon = item.InvenIndex
+ }
+ if item.ID == 701 {
+ shield = item.InvenIndex
+ }
+ }
+ _, e = totalWarCall(ctx, rt, "/TotalWarDeckSave", totalWarDeckRequest(2, deck...))
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckInfo", request(3))
+ if e != nil {
+ return e
+ }
+ rows, _ := msgs(body, 1)
+ if len(rows) != 3 || n(rows[0], 2) != 102 || n(rows[1], 2) != 101 {
+ t.Fatal("formation skill order or multiple costumes on same character lost on reopen")
+ }
+ if totalWarEquipmentFor(t, body, 2, 81, 0) != weapon || totalWarEquipmentFor(t, body, 2, 82, 1) != shield {
+ t.Fatal("initial formation did not copy live equipment")
+ }
+ update := wire.AppendBytes(request(4), 2, totalWarContent(81, 0, shield))
+ update = wire.AppendBytes(update, 2, totalWarContent(82, weapon, 0))
+ _, e = totalWarCall(ctx, rt, "/TotalWarEquipSave", update)
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckInfo", request(5))
+ if e != nil {
+ return e
+ }
+ if totalWarEquipmentFor(t, body, 2, 81, 1) != shield || totalWarEquipmentFor(t, body, 2, 82, 0) != weapon {
+ t.Fatal("independent equipment transfer did not survive transaction reopen")
+ }
+ for _, item := range rt.equipment.All(ctx) {
+ if item.ID == 700 && item.UseChar != 81 || item.ID == 701 && item.UseChar != 82 {
+ t.Fatal("total war changed normal equipment ownership")
+ }
+ }
+ return nil
+ }, false)
+ for seq, bad := range [][]byte{totalWarContent(81, weapon), totalWarContent(81, 999999), totalWarContent(81, shield)} {
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarEquipSave", wire.AppendBytes(request(uint64(10+seq)), 2, bad))
+ return e
+ }, true)
+ }
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ before, e := totalWarCall(ctx, rt, "/TotalWarDeckInfo", request(20))
+ if e != nil {
+ return e
+ }
+ if totalWarEquipmentFor(t, before, 2, 82, 0) != weapon {
+ t.Fatal("rejected equipment updates changed saved transfer")
+ }
+ body, e := totalWarCall(ctx, rt, "/TotalWarContentsItemRenew", request(21))
+ if e != nil {
+ return e
+ }
+ if totalWarEquipmentFor(t, body, 1, 81, 0) != weapon || totalWarEquipmentFor(t, body, 1, 82, 1) != shield {
+ t.Fatal("renew did not restore live equipment")
+ }
+ return nil
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckInfo", request(22))
+ if e == nil && totalWarEquipmentFor(t, body, 2, 81, 0) != weapon {
+ t.Fatal("renew was not persisted")
+ }
+ return e
+ }, false)
+}
+
+func TestTotalWarPresetsMetadataDeleteAndSlotCurrency(t *testing.T) {
+ f := newTotalWarFixture(t)
+ preset := wire.AppendVarint(nil, 1, 0)
+ preset = wire.AppendBytes(preset, 2, []byte("Boss"))
+ preset = wire.AppendVarint(preset, 3, 11)
+ preset = wire.AppendBytes(preset, 5, totalWarDeckEntry(0, 102, 81))
+ preset = wire.AppendBytes(preset, 5, totalWarDeckEntry(0, 101, 81))
+ saveRequest := wire.AppendBytes(request(30), 2, preset)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSave", saveRequest)
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSlotAdd", request(31, 1))
+ return e
+ }, true)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ if rt.wallet.Snapshot(ctx).Gold != 10000 {
+ t.Fatal("current GameData five-slot cap charged gold")
+ }
+ metadata := wire.AppendBytes(request(32), 2, []byte("Renamed"))
+ metadata = wire.AppendVarint(metadata, 3, 11)
+ metadata = wire.AppendVarint(metadata, 4, 3)
+ metadata = wire.AppendVarint(metadata, 5, 0)
+ _, e := totalWarCall(ctx, rt, "/TotalWarPresetInfoChange", metadata)
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetInfo", request(33))
+ if e != nil {
+ return e
+ }
+ rows, _ := msgs(body, 1)
+ if len(rows) != 1 {
+ t.Fatal("preset missing on reopen")
+ }
+ name, _, _ := wire.Bytes(rows[0], 2)
+ deck, _ := msgs(rows[0], 5)
+ if string(name) != "Renamed" || n(rows[0], 4) != 3 || len(deck) != 2 || n(deck[0], 2) != 102 || n(deck[1], 2) != 101 {
+ t.Fatal("metadata change changed saved skill order")
+ }
+ deleteRequest := wire.AppendBytes(request(34), 2, []byte{0, 4})
+ _, e = totalWarCall(ctx, rt, "/TotalWarPresetDelete", deleteRequest)
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetInfo", request(35))
+ if len(body) != 0 {
+ t.Fatal("deleted preset still present")
+ }
+ slots, se := rt.service.TotalWarPresetSlotCount(ctx)
+ if se != nil || slots != 5 {
+ t.Fatal("deleting preset removed purchased capacity")
+ }
+ return e
+ }, false)
+ // A design with seven purchasable slots exercises the shared paid-slot rule.
+ f.design.TotalWarPresets.Maximum = 8
+ purchase := request(36, 2)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSlotAdd", purchase)
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSlotAdd", purchase)
+ if e != nil {
+ return e
+ }
+ if rt.wallet.Snapshot(ctx).Gold != 6000 {
+ t.Fatal("two slots must cost 4000 gold once across reopen")
+ }
+ slots, e := rt.service.TotalWarPresetSlotCount(ctx)
+ if e != nil || slots != 7 {
+ t.Fatal("purchased slots missing on reopen")
+ }
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSlotAdd", request(36, 1))
+ return e
+ }, true)
+ f.design.TotalWarPresets.Price = 7000
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSlotAdd", request(37, 1))
+ return e
+ }, true)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ if rt.wallet.Snapshot(ctx).Gold != 6000 {
+ t.Fatal("failed purchase charged currency")
+ }
+ slots, e := rt.service.TotalWarPresetSlotCount(ctx)
+ if slots != 7 {
+ t.Fatal("failed purchase created a slot")
+ }
+ return e
+ }, false)
+}
+
+type failTotalWarSave struct{ stateio.AtomicEntryStore }
+
+func (f failTotalWarSave) SaveWithEntries(domain string, core []byte, entries []stateio.EntryMutation) error {
+ if domain == "missions" {
+ return fmt.Errorf("injected mission write failure")
+ }
+ return f.AtomicEntryStore.SaveWithEntries(domain, core, entries)
+}
+func TestTotalWarSlotDebitRollsBackWithFormationPersistence(t *testing.T) {
+ f := newTotalWarFixture(t)
+ f.design.TotalWarPresets.Maximum = 8
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ ctx.State = failTotalWarSave{ctx.State}
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSlotAdd", request(40, 2))
+ return e
+ }, true)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ if rt.wallet.Snapshot(ctx).Gold != 10000 {
+ t.Fatal("formation failure committed wallet debit")
+ }
+ slots, e := rt.service.TotalWarPresetSlotCount(ctx)
+ if slots != 5 {
+ t.Fatal("failed command changed capacity")
+ }
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSlotAdd", request(40, 2))
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ if rt.wallet.Snapshot(ctx).Gold != 6000 {
+ t.Fatal("retry after rollback did not pay exactly once")
+ }
+ return nil
+ }, false)
+}
+
+func TestTotalWarInvalidOwnershipAndPresetFailuresKeepFormation(t *testing.T) {
+ f := newTotalWarFixture(t)
+ valid := totalWarDeckRequest(50, totalWarDeckEntry(0, 101, 81), totalWarDeckEntry(1, 103, 82))
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckSave", valid)
+ return e
+ }, false)
+ for seq, entries := range [][][]byte{{totalWarDeckEntry(0, 101, 82)}, {totalWarDeckEntry(0, 999, 81)}, {totalWarDeckEntry(0, 101, 81), totalWarDeckEntry(1, 101, 81)}, {totalWarDeckEntry(2, 101, 81)}} {
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckSave", totalWarDeckRequest(uint64(51+seq), entries...))
+ return e
+ }, true)
+ }
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckInfo", request(60))
+ rows, _ := msgs(body, 1)
+ if len(rows) != 2 || !bytes.Equal(rows[0], totalWarDeckEntry(0, 101, 81)) || !bytes.Equal(rows[1], totalWarDeckEntry(1, 103, 82)) {
+ t.Fatal("rejected decks changed saved formation")
+ }
+ return e
+ }, false)
+}
+
+func TestTotalWarTwentyAttackersAndOwnedCostumeBoundary(t *testing.T) {
+ f := newTotalWarFixture(t)
+ var deck [][]byte
+ for i := range uint64(21) {
+ f.costumes = append(f.costumes, roster.Costume{InvenIndex: 1001 + i, ID: 2001 + i, UseChar: 81})
+ deck = append(deck, totalWarDeckEntry(0, 1001+i, 81))
+ }
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckSave", totalWarDeckRequest(70, deck...))
+ return e
+ }, true)
+ deck[20] = totalWarDeckEntry(1, 1021, 81)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckSave", totalWarDeckRequest(71, deck...))
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckInfo", request(72))
+ rows, _ := msgs(body, 1)
+ if len(rows) != 21 || n(rows[20], 1) != 1 {
+ t.Fatal("twenty attackers plus a cheering owned costume should persist")
+ }
+ return e
+ }, false)
+}
+
+func TestTotalWarSavedBattleEquipmentAndFrozenBestCompletion(t *testing.T) {
+ f := newTotalWarFixture(t)
+ f.completion = func(ctx command.Context, id string, score uint64, costumes []uint64) error {
+ if id != "login:81" || score != 300 || len(costumes) != 2 || costumes[0] != 92 || costumes[1] != 91 {
+ return fmt.Errorf("completion lost start-time attackers or score")
+ }
+ return ctx.State.PutEntry("missions", "totalwar_test_publication", "highest", []byte("300:92:91"))
+ }
+ formation := [][]byte{totalWarDeckEntry(0, 102, 81), totalWarDeckEntry(0, 101, 81), totalWarDeckEntry(1, 103, 82)}
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckSave", totalWarDeckRequest(80, formation...))
+ return e
+ }, false)
+ var start []byte
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckInfo", request(800))
+ if e != nil {
+ return e
+ }
+ contents, _ := msgs(body, 2)
+ start = request(81, 1)
+ for i, entry := range formation {
+ charID := uint64(71)
+ if n(entry, 3) == 82 {
+ charID = 72
+ }
+ blue := wire.AppendVarint(nil, 2, n(entry, 3))
+ blue = wire.AppendVarint(blue, 3, charID)
+ blue = wire.AppendVarint(blue, 6, n(entry, 2))
+ costume, _ := rt.collection.CostumeByIndex(n(entry, 2))
+ blue = wire.AppendVarint(blue, 7, costume.ID)
+ blue = wire.AppendVarint(blue, 28, n(entry, 1))
+ if n(entry, 1) == 0 {
+ blue = wire.AppendVarint(blue, 1, uint64(i+1))
+ }
+ for _, content := range contents {
+ if n(content, 1) != n(entry, 3) {
+ continue
+ }
+ blue = wire.AppendVarint(blue, 29, n(content, 3))
+ refs, _ := msgs(content, 2)
+ for _, ref := range refs {
+ if id := n(ref, 1); id != 0 {
+ blue = wire.AppendVarint(blue, 12, id)
+ }
+ }
+ }
+ start = wire.AppendBytes(start, 3, blue)
+ }
+ red := wire.AppendVarint(nil, 1, 99)
+ red = wire.AppendVarint(red, 3, 95)
+ red = wire.AppendVarint(red, 4, 1000000)
+ red = wire.AppendVarint(red, 5, 1)
+ start = wire.AppendBytes(start, 4, red)
+ return nil
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ invalid := request(810, 1)
+ blue, _ := msgs(start, 3)
+ for i, row := range blue {
+ if i == 0 {
+ row = wire.AppendVarint(row, 12, 99999)
+ }
+ invalid = wire.AppendBytes(invalid, 3, row)
+ }
+ red, _ := msgs(start, 4)
+ invalid = wire.AppendBytes(invalid, 4, red[0])
+ _, e := totalWarCall(ctx, rt, "/TotalWarBattleStart", invalid)
+ return e
+ }, true)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarBattleEnd", request(811))
+ return e
+ }, true)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarBattleStart", start)
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckSave", totalWarDeckRequest(82, formation[1], formation[0], formation[2]))
+ return e
+ }, false)
+ end := wire.AppendBytes(request(83), 2, wire.AppendVarint(wire.AppendVarint(nil, 1, 92), 2, 100))
+ end = wire.AppendBytes(end, 2, wire.AppendVarint(wire.AppendVarint(nil, 1, 91), 2, 200))
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarBattleEnd", end)
+ return e
+ }, false)
+ if e := f.repo.Close(); e != nil {
+ t.Fatal(e)
+ }
+ reopened, e := accountstate.Open(f.path)
+ if e != nil {
+ t.Fatal(e)
+ }
+ f.repo = reopened
+ t.Cleanup(func() {
+ if e := reopened.Close(); e != nil {
+ t.Error(e)
+ }
+ })
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ if _, e := totalWarCall(ctx, rt, "/TotalWarBattleEnd", end); e != nil {
+ return e
+ }
+ raw, found, e := ctx.State.LoadEntry("missions", "totalwar_test_publication", "highest")
+ if e != nil {
+ return e
+ }
+ if !found || string(raw) != "300:92:91" {
+ t.Fatal("highest-score start-time publication missing after SQLite reopen")
+ }
+ _, e = totalWarCall(ctx, rt, "/TotalWarReward", request(84))
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarReward", request(84))
+ if e != nil {
+ return e
+ }
+ if rt.wallet.Snapshot(ctx).Gold != 10003 {
+ t.Fatal("300 damage must credit the 3-gold tier once")
+ }
+ return nil
+ }, false)
+}
+
+func TestTotalWarPresetRejectsInvalidMetadataAndDeletionAtomically(t *testing.T) {
+ f := newTotalWarFixture(t)
+ preset := wire.AppendVarint(nil, 1, 0)
+ preset = wire.AppendBytes(preset, 2, []byte("Boss"))
+ preset = wire.AppendVarint(preset, 3, 11)
+ preset = wire.AppendBytes(preset, 5, totalWarDeckEntry(0, 101, 81))
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSave", wire.AppendBytes(request(90), 2, preset))
+ return e
+ }, false)
+ for i, tc := range []struct {
+ name string
+ metadata []byte
+ }{
+ {"unavailable_slot", wire.AppendVarint(nil, 5, 5)},
+ {"invalid_name", wire.AppendBytes(wire.AppendVarint(nil, 5, 0), 2, []byte(""))},
+ {"unknown_icon", wire.AppendVarint(wire.AppendVarint(nil, 5, 0), 3, 999)},
+ {"undefined_color", wire.AppendVarint(wire.AppendVarint(nil, 5, 0), 4, 6)},
+ {"icon_wrong_wire_type", wire.AppendBytes(wire.AppendVarint(nil, 5, 0), 3, []byte{11})},
+ {"slot_wrong_wire_type", wire.AppendBytes(nil, 5, []byte{0})},
+ {"icon_repeated", wire.AppendVarint(wire.AppendVarint(nil, 3, 11), 3, 11)},
+ {"icon_invalid_then_valid", wire.AppendVarint(wire.AppendVarint(nil, 3, 999), 3, 11)},
+ {"icon_valid_then_invalid", wire.AppendVarint(wire.AppendVarint(nil, 3, 11), 3, 999)},
+ {"slot_repeated", wire.AppendVarint(wire.AppendVarint(nil, 5, 0), 5, 0)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarPresetInfoChange", append(request(uint64(1000+i)), tc.metadata...))
+ return e
+ }, true)
+ })
+ }
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarPresetDelete", wire.AppendBytes(request(96), 2, []byte{0, 5}))
+ return e
+ }, true)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetInfo", request(97))
+ if e != nil {
+ return e
+ }
+ rows, _ := msgs(body, 1)
+ if len(rows) != 1 || !bytes.Equal(rows[0], preset) {
+ t.Fatal("invalid metadata or mixed valid/invalid deletion changed preset")
+ }
+ return nil
+ }, false)
+}
+
+func TestTotalWarMalformedRequestScalarsPreserveFormationAndGold(t *testing.T) {
+ f := newTotalWarFixture(t)
+ f.design.TotalWarPresets.Maximum = 8
+ formation := totalWarDeckEntry(0, 101, 81)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckSave", totalWarDeckRequest(2000, formation))
+ return e
+ }, false)
+ for _, tc := range []struct {
+ name, path string
+ request []byte
+ }{
+ {"duplicate_sequence", "/TotalWarDeckSave", wire.AppendVarint(totalWarDeckRequest(2001, totalWarDeckEntry(1, 101, 81)), 1, 2001)},
+ {"wrong_sequence_type", "/TotalWarDeckSave", wire.AppendBytes(totalWarDeckRequest(2002, totalWarDeckEntry(1, 101, 81)), 1, []byte{1})},
+ {"repeated_role", "/TotalWarDeckSave", totalWarDeckRequest(2003, wire.AppendVarint(formation, 1, 1))},
+ {"wrong_character_type", "/TotalWarDeckSave", totalWarDeckRequest(2004, wire.AppendBytes(formation, 3, []byte{81}))},
+ {"repeated_purchase_count", "/TotalWarDeckPresetSlotAdd", wire.AppendVarint(request(2005, 1), 2, 1)},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, tc.path, tc.request)
+ return e
+ }, true)
+ })
+ }
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckInfo", request(2010))
+ if e != nil {
+ return e
+ }
+ rows, _ := msgs(body, 1)
+ if len(rows) != 1 || !bytes.Equal(rows[0], formation) {
+ t.Fatal("malformed scalar changed formation")
+ }
+ slots, e := rt.service.TotalWarPresetSlotCount(ctx)
+ if slots != 5 || rt.wallet.Snapshot(ctx).Gold != 10000 {
+ t.Fatal("malformed purchase changed capacity or gold")
+ }
+ return e
+ }, false)
+}
+
+func TestTotalWarPermanentSentinelExcludesTemporaryAndExpiredCharacters(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ character roster.Character
+ }{
+ {"expired_normal", roster.Character{InvenIndex: 83, ID: 73, Level: 1, ExpiryTime: 1}},
+ {"story_zero_expiry", roster.Character{InvenIndex: roster.StoryCharacterIndexBase, ID: 73, Level: 1}},
+ {"charm_permanent_expiry", roster.Character{InvenIndex: roster.CharmCharacterIndexBase, ID: 73, Level: 1, ExpiryTime: ^uint64(0) - 32399999}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := newTotalWarFixture(t, roster.Character{InvenIndex: 81, ID: 71, Level: 1, ExpiryTime: ^uint64(0) - 32399999}, roster.Character{InvenIndex: 82, ID: 72, Level: 1}, tc.character)
+ f.costumes = []roster.Costume{{InvenIndex: 101, ID: 91, UseChar: 81}, {InvenIndex: 102, ID: 92, UseChar: 81}, {InvenIndex: 103, ID: 93, UseChar: 82}, {InvenIndex: 104, ID: 94, UseChar: tc.character.InvenIndex}}
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckSave", totalWarDeckRequest(2100, totalWarDeckEntry(0, 101, 81)))
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckSave", totalWarDeckRequest(2101, totalWarDeckEntry(0, 104, tc.character.InvenIndex)))
+ return e
+ }, true)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ _, e := totalWarCall(ctx, rt, "/TotalWarEquipSave", wire.AppendBytes(request(2102), 2, totalWarContent(tc.character.InvenIndex, 0, 0, 0, 0, 0)))
+ return e
+ }, true)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ body, e := totalWarCall(ctx, rt, "/TotalWarContentsItemRenew", request(2103))
+ if e != nil {
+ return e
+ }
+ rows, _ := msgs(body, 1)
+ if len(rows) != 2 {
+ t.Fatal("renew did not retain both permanent expiry representations")
+ }
+ for _, row := range rows {
+ if n(row, 1) != 81 && n(row, 1) != 82 {
+ t.Fatal("renew included temporary or expired character")
+ }
+ }
+ return nil
+ }, false)
+ })
+ }
+}
+
+func TestTotalWarPresetNameApprovalPreservesStoredMetadata(t *testing.T) {
+ f := newTotalWarFixture(t)
+ preset := wire.AppendVarint(nil, 1, 0)
+ preset = wire.AppendBytes(preset, 2, []byte("Approved"))
+ preset = wire.AppendBytes(preset, 5, totalWarDeckEntry(0, 101, 81))
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ rt.service.AttachTotalWarTextCheck(func(_ command.Context, scope, name string) error {
+ if scope != "total_war_preset_name" || name != "Approved" {
+ return fmt.Errorf("unexpected approval request")
+ }
+ return nil
+ })
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSave", wire.AppendBytes(request(2200), 2, preset))
+ return e
+ }, false)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ rt.service.AttachTotalWarTextCheck(func(_ command.Context, scope, name string) error {
+ if scope != "total_war_preset_name" || name != "Rejected" {
+ t.Fatal("wrong approval scope or name")
+ }
+ return fmt.Errorf("text rejected")
+ })
+ _, e := totalWarCall(ctx, rt, "/TotalWarPresetInfoChange", wire.AppendBytes(request(2201), 2, []byte("Rejected")))
+ return e
+ }, true)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ rt.service.AttachTotalWarTextCheck(nil)
+ unchecked := wire.AppendBytes(wire.AppendVarint(nil, 1, 0), 2, []byte("Unchecked"))
+ _, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetSave", wire.AppendBytes(request(2202), 2, unchecked))
+ return e
+ }, true)
+ f.command(t, func(ctx command.Context, rt totalWarRuntime) error {
+ rt.service.AttachTotalWarTextCheck(func(command.Context, string, string) error { t.Fatal("read requested new text approval"); return nil })
+ body, e := totalWarCall(ctx, rt, "/TotalWarDeckPresetInfo", request(2203))
+ if e != nil {
+ return e
+ }
+ rows, _ := msgs(body, 1)
+ if len(rows) != 1 || !bytes.Equal(rows[0], preset) {
+ t.Fatal("rejected name changed saved preset")
+ }
+ return nil
+ }, false)
+}
diff --git a/go/internal/server/domain/battle/hunting/protocol_adapter.go b/go/internal/server/domain/battle/hunting/protocol_adapter.go
index ed33f99..cdff59e 100644
--- a/go/internal/server/domain/battle/hunting/protocol_adapter.go
+++ b/go/internal/server/domain/battle/hunting/protocol_adapter.go
@@ -1,6 +1,7 @@
package hunting
import (
+ "bd2server/internal/common/util"
"bd2server/internal/common/versionconfig"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
@@ -8,13 +9,11 @@ import (
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/stateio"
"bytes"
- "crypto/rand"
"encoding/binary"
"encoding/json"
"fmt"
"maps"
"math"
- "math/big"
"sort"
"strconv"
"strings"
@@ -522,13 +521,7 @@ func (s *Service) handleDispatch(ctx command.Context, path string, req []byte, s
if !sky && s.state.Free < cost && s.state.Bonus < cost-s.state.Free {
return code, nil, true, fmt.Errorf("hunting: insufficient hunting AP")
}
- rewards, e := d.Roll(count, func(n uint64) (uint64, error) {
- v, e := rand.Int(rand.Reader, new(big.Int).SetUint64(n))
- if e != nil {
- return 0, e
- }
- return v.Uint64(), nil
- })
+ rewards, e := d.Roll(count, util.RandomUint64N)
if e != nil {
return code, nil, true, e
}
@@ -559,13 +552,7 @@ func (s *Service) handleDispatch(ctx command.Context, path string, req []byte, s
now := uint64(time.Now().UnixMilli())
runs := make([][]gamedata.BattleReward, count)
for i := range runs {
- runs[i], e = d.Roll(1, func(n uint64) (uint64, error) {
- v, e := rand.Int(rand.Reader, new(big.Int).SetUint64(n))
- if e != nil {
- return 0, e
- }
- return v.Uint64(), nil
- })
+ runs[i], e = d.Roll(1, util.RandomUint64N)
if e != nil {
return code, nil, true, e
}
diff --git a/go/internal/server/domain/battle/ib/service.go b/go/internal/server/domain/battle/ib/service.go
new file mode 100644
index 0000000..a4bea5b
--- /dev/null
+++ b/go/internal/server/domain/battle/ib/service.go
@@ -0,0 +1,729 @@
+package ib
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "math/big"
+ "slices"
+
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+type Economy interface {
+ Apply(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error)
+}
+type Period struct {
+ Season, Regular uint64
+ Open bool
+}
+type Options struct {
+ Period func(command.Context) (Period, error)
+ CostumeLevel func(command.Context, uint64) (uint64, error)
+}
+type item struct{ Index, Type, ID, Level uint64 }
+type placement struct{ Index, Position, Rotation uint64 }
+type shopItem struct {
+ Slot, Type, ID, Price, Original uint64
+ Discount, Reserved, Sold bool
+}
+type play struct {
+ Dungeon, Stage, Life, Coin, Season, Refreshes uint64
+ Entered bool
+}
+type receipt struct {
+ Digest [32]byte
+ Reply []byte
+}
+type snapshot struct {
+ Version string
+ Season, Run, NextIndex uint64
+ Play play
+ Cleared map[uint64]bool
+ Items map[uint64]item
+ Deck []placement
+ Shop []shopItem
+ Process []byte
+ Receipts map[string]receipt
+}
+type Service struct {
+ store stateio.Store
+ design *gamedata.IBDesign
+ economy Economy
+ options Options
+ state snapshot
+}
+
+func Open(ctx command.Context, store stateio.Store, d *gamedata.IBDesign, e Economy, o Options) (*Service, error) {
+ if store == nil || d == nil || e == nil || o.Period == nil {
+ return nil, errors.New("ib: missing dependency")
+ }
+ s := &Service{store: store, design: d, economy: e, options: o, state: snapshot{Version: versionconfig.State(), NextIndex: 1, Cleared: map[uint64]bool{}, Items: map[uint64]item{}, Receipts: map[string]receipt{}}}
+ b, err := store.Load(ctx.State, "ib")
+ if err != nil {
+ return nil, err
+ }
+ if b != nil {
+ if err = stateio.RequireExactJSONObject(b, "Version", "Season", "Run", "NextIndex", "Play", "Cleared", "Items", "Deck", "Shop", "Process", "Receipts"); err != nil {
+ return nil, err
+ }
+ if err = json.Unmarshal(b, &s.state); err != nil {
+ return nil, err
+ }
+ if err = s.validate(); err != nil {
+ return nil, err
+ }
+ }
+ return s, nil
+}
+func (s *Service) validate() error {
+ if s.state.Version != versionconfig.State() || s.state.Cleared == nil || s.state.Items == nil || s.state.Receipts == nil || s.state.NextIndex == 0 || s.state.NextIndex > math.MaxInt32 {
+ return errors.New("ib: invalid state")
+ }
+ for id, yes := range s.state.Cleared {
+ if _, ok := s.design.Dungeons[id]; !ok || !yes {
+ return errors.New("ib: invalid clear record")
+ }
+ }
+ for index, i := range s.state.Items {
+ d, ok := s.design.Items[i.ID]
+ if !ok || index != i.Index || index == 0 || index >= s.state.NextIndex || i.Type != d.Type {
+ return errors.New("ib: invalid item")
+ }
+ if i.Level > 0 {
+ if _, ok = s.design.UpgradeCosts[[3]uint64{i.Type, d.TypeID, i.Level + 1}]; !ok {
+ return errors.New("ib: invalid item level")
+ }
+ }
+ }
+ if s.state.Play.Dungeon == 0 {
+ if len(s.state.Items) > 0 || len(s.state.Deck) > 0 || len(s.state.Shop) > 0 || len(s.state.Process) > 0 || s.state.Play != (play{}) {
+ return errors.New("ib: orphaned run")
+ }
+ return nil
+ }
+ d, _, err := s.stage()
+ if err != nil {
+ return err
+ }
+ if s.state.Play.Life == 0 || s.state.Play.Life > d.Life || s.state.Play.Season != s.state.Season || s.state.Play.Coin > math.MaxInt32 || s.state.Play.Entered != (len(s.state.Process) > 0) {
+ return errors.New("ib: invalid run")
+ }
+ if err := s.validateDeck(s.state.Deck); err != nil {
+ return err
+ }
+ if len(s.state.Shop) != 4 {
+ return errors.New("ib: invalid shop")
+ }
+ for slot, i := range s.state.Shop {
+ d, ok := s.design.Items[i.ID]
+ if !ok || i.Type != d.Type || i.Slot != uint64(slot) || i.Original != d.Price || i.Price > i.Original || i.Reserved && i.Sold {
+ return errors.New("ib: invalid shop item")
+ }
+ }
+ return nil
+}
+func (s *Service) save(ctx command.Context) error {
+ b, e := json.Marshal(s.state)
+ if e != nil {
+ return e
+ }
+ return s.store.Save(ctx.State, "ib", b)
+}
+func value(b []byte, n int) uint64 { v, _, _ := wire.Varint(b, n); return v }
+func scalars(values ...uint64) []byte {
+ var b []byte
+ for n, v := range values {
+ if v != 0 {
+ b = wire.AppendVarint(b, n+1, v)
+ }
+ }
+ return b
+}
+func itemWire(i item) []byte { return scalars(i.Index, i.Type, i.ID, i.Level) }
+func deckWire(p placement) []byte { return scalars(p.Index, p.Position, p.Rotation) }
+func shopWire(i shopItem) []byte {
+ b := scalars(i.Slot, i.Type, i.ID, i.Price, i.Original)
+ for n, v := range []bool{i.Discount, i.Reserved, i.Sold} {
+ if v {
+ b = wire.AppendVarint(b, n+6, 1)
+ }
+ }
+ return b
+}
+func (s *Service) playWire() []byte {
+ p := s.state.Play
+ b := scalars(p.Dungeon, p.Stage, p.Life, p.Coin, p.Season, p.Refreshes)
+ if p.Entered {
+ b = wire.AppendVarint(b, 7, 1)
+ }
+ return b
+}
+func (s *Service) itemsWire(b []byte, field int) []byte {
+ ids := make([]uint64, 0, len(s.state.Items))
+ for id := range s.state.Items {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ for _, id := range ids {
+ b = wire.AppendBytes(b, field, itemWire(s.state.Items[id]))
+ }
+ return b
+}
+func (s *Service) decksWire(b []byte, field int) []byte {
+ for _, p := range s.state.Deck {
+ b = wire.AppendBytes(b, field, deckWire(p))
+ }
+ return b
+}
+func (s *Service) shopWire() []byte {
+ var b []byte
+ for _, i := range s.state.Shop {
+ b = wire.AppendBytes(b, 1, shopWire(i))
+ }
+ return b
+}
+func randomBelow(n uint64) (uint64, error) {
+ if n == 0 {
+ return 0, errors.New("ib: empty random range")
+ }
+ v, e := rand.Int(rand.Reader, new(big.Int).SetUint64(n))
+ if e != nil {
+ return 0, e
+ }
+ return v.Uint64(), nil
+}
+
+var codes = map[string]int{"/IbMainInfo": 558, "/IbItemInfo": 559, "/IbDeckInfo": 560, "/IbDeckSave": 561, "/IbShopRefresh": 562, "/IbShopBuy": 563, "/IbItemSell": 564, "/IbDungeonEnter": 565, "/IbStageStart": 566, "/IbStageEnd": 567, "/IbDungeonGiveUp": 568, "/IbItemUpgrade": 577, "/IbShopItemReserve": 580, "/IbShopInfo": 621}
+
+func (s *Service) Handle(ctx command.Context, path string, b []byte) (int, []byte, bool, error) {
+ code, ok := codes[path]
+ if !ok {
+ return 0, nil, false, nil
+ }
+ if err := wire.Walk(b, func(wire.Field) error { return nil }); err != nil {
+ return code, nil, true, err
+ }
+ seq := value(b, 1)
+ if seq == 0 || seq > math.MaxInt32 {
+ return code, nil, true, errors.New("ib: missing sequence")
+ }
+ query := path == "/IbMainInfo" || path == "/IbItemInfo" || path == "/IbDeckInfo" || path == "/IbShopInfo"
+ key := fmt.Sprintf("%s:%s:%d", ctx.SessionID, path, seq)
+ digest := sha256.Sum256(append([]byte(path), b...))
+ if !query {
+ if r, ok := s.state.Receipts[key]; ok {
+ if r.Digest != digest {
+ return code, nil, true, errors.New("ib: changed replay")
+ }
+ return code, slices.Clone(r.Reply), true, nil
+ }
+ }
+ before, _ := json.Marshal(s.state)
+ period, err := s.options.Period(ctx)
+ if err == nil && period.Season != 0 {
+ if _, ok := s.design.Seasons[period.Season]; !ok {
+ err = errors.New("ib: undefined season")
+ }
+ }
+ reset := s.state.Season != 0 && s.state.Season != period.Season
+ if err == nil && s.state.Season != period.Season {
+ s.clearRun()
+ s.state.Cleared = map[uint64]bool{}
+ s.state.Season = period.Season
+ }
+ var out []byte
+ if err == nil {
+ out, err = s.handle(ctx, path, b, period, reset)
+ }
+ if err == nil {
+ if !query {
+ s.state.Receipts[key] = receipt{digest, slices.Clone(out)}
+ }
+ err = s.save(ctx)
+ }
+ if err != nil {
+ var restored snapshot
+ _ = json.Unmarshal(before, &restored)
+ s.state = restored
+ return code, nil, true, err
+ }
+ return code, out, true, nil
+}
+func (s *Service) clearRun() {
+ s.state.Play = play{}
+ s.state.Items = map[uint64]item{}
+ s.state.Deck = nil
+ s.state.Shop = nil
+ s.state.Process = nil
+}
+func (s *Service) stage() (gamedata.IBDungeon, gamedata.IBStage, error) {
+ d, ok := s.design.Dungeons[s.state.Play.Dungeon]
+ if ok {
+ for _, stage := range d.Stages {
+ if stage.ID == s.state.Play.Stage {
+ return d, stage, nil
+ }
+ }
+ }
+ return d, gamedata.IBStage{}, errors.New("ib: no active stage")
+}
+func (s *Service) preparing() error {
+ if s.state.Play.Dungeon == 0 {
+ return errors.New("ib: no active dungeon")
+ }
+ if s.state.Play.Entered {
+ return errors.New("ib: battle in progress")
+ }
+ return nil
+}
+func (s *Service) spend(cost uint64) error {
+ if cost > s.state.Play.Coin {
+ return errors.New("ib: insufficient soul tokens")
+ }
+ s.state.Play.Coin -= cost
+ return nil
+}
+func (s *Service) credit(n uint64) error {
+ if n > math.MaxInt32-s.state.Play.Coin {
+ return errors.New("ib: token overflow")
+ }
+ s.state.Play.Coin += n
+ return nil
+}
+func (s *Service) addItem(id uint64) (item, error) {
+ d, ok := s.design.Items[id]
+ if !ok || s.state.NextIndex >= math.MaxInt32 {
+ return item{}, errors.New("ib: cannot create item")
+ }
+ i := item{Index: s.state.NextIndex, Type: d.Type, ID: id}
+ s.state.NextIndex++
+ s.state.Items[i.Index] = i
+ return i, nil
+}
+
+func (s *Service) handle(ctx command.Context, path string, b []byte, period Period, reset bool) ([]byte, error) {
+ a, c := value(b, 2), value(b, 3)
+ switch path {
+ case "/IbMainInfo":
+ out := wire.AppendBytes(nil, 1, s.playWire())
+ if reset {
+ out = wire.AppendVarint(out, 2, 1)
+ }
+ ids := make([]uint64, 0, len(s.state.Cleared))
+ for id := range s.state.Cleared {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ for _, id := range ids {
+ out = wire.AppendVarint(out, 3, id)
+ }
+ return wire.AppendVarint(out, 4, period.Regular), nil
+ case "/IbItemInfo":
+ return s.itemsWire(nil, 1), nil
+ case "/IbDeckInfo":
+ return s.decksWire(nil, 1), nil
+ }
+ if !period.Open || period.Season == 0 {
+ return nil, errors.New("ib: season closed")
+ }
+ switch path {
+ case "/IbDungeonEnter":
+ if s.state.Play.Dungeon != 0 {
+ return nil, errors.New("ib: active dungeon must be abandoned first")
+ }
+ d, ok := s.design.Dungeons[a]
+ if !ok || !slices.Contains(s.design.Seasons[period.Season], a) || d.Unlock != 0 && !s.state.Cleared[d.Unlock] {
+ return nil, errors.New("ib: dungeon locked")
+ }
+ s.state.Run++
+ s.state.Play = play{Dungeon: a, Stage: d.Stages[0].ID, Life: d.Life, Coin: d.Stages[0].Credit, Season: period.Season}
+ for _, p := range s.design.Decks[s.design.StartDeck] {
+ i, e := s.addItem(p.ItemID)
+ if e != nil {
+ return nil, e
+ }
+ s.state.Deck = append(s.state.Deck, placement{i.Index, p.Position, p.Rotation})
+ }
+ if err := s.refreshShop(false); err != nil {
+ return nil, err
+ }
+ out := wire.AppendBytes(nil, 1, s.playWire())
+ out = s.itemsWire(out, 2)
+ return s.decksWire(out, 3), nil
+ case "/IbDungeonGiveUp":
+ s.clearRun()
+ return nil, nil
+ case "/IbStageStart":
+ _, stage, err := s.stage()
+ if err != nil {
+ return nil, err
+ }
+ if a != s.state.Play.Dungeon || c != stage.ID {
+ return nil, errors.New("ib: wrong stage")
+ }
+ if !s.state.Play.Entered {
+ if err = s.validateDeck(s.state.Deck); err != nil {
+ return nil, err
+ }
+ if len(s.state.Deck) == 0 {
+ return nil, errors.New("ib: deploy items before battle")
+ }
+ seed, err := randomBelow(math.MaxInt32)
+ if err != nil {
+ return nil, err
+ }
+ process := scalars(30, seed+1, a, c)
+ process = s.decksWire(process, 5)
+ process = s.itemsWire(process, 6)
+ for n, p := range s.design.Decks[stage.EnemyDeck] {
+ index := uint64(n + 1)
+ d := s.design.Items[p.ItemID]
+ process = wire.AppendBytes(process, 7, deckWire(placement{index, p.Position, p.Rotation}))
+ process = wire.AppendBytes(process, 8, itemWire(item{Index: index, Type: d.Type, ID: d.ID}))
+ }
+ s.state.Process = process
+ s.state.Play.Entered = true
+ }
+ return wire.AppendBytes(nil, 1, []byte(base64.StdEncoding.EncodeToString(s.state.Process))), nil
+ case "/IbStageEnd":
+ return s.end(ctx, a)
+ }
+ if err := s.preparing(); err != nil {
+ return nil, err
+ }
+ switch path {
+ case "/IbShopInfo":
+ return s.shopWire(), nil
+ case "/IbDeckSave":
+ var deck []placement
+ err := wire.Walk(b, func(f wire.Field) error {
+ if f.Number != 2 {
+ return nil
+ }
+ if f.Type != 2 {
+ return wire.ErrMalformed
+ }
+ if e := wire.Walk(f.Value, func(wire.Field) error { return nil }); e != nil {
+ return e
+ }
+ deck = append(deck, placement{value(f.Value, 1), value(f.Value, 2), value(f.Value, 3)})
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ if err = s.validateDeck(deck); err != nil {
+ return nil, err
+ }
+ s.state.Deck = deck
+ return nil, nil
+ case "/IbShopItemReserve":
+ if a >= uint64(len(s.state.Shop)) || s.state.Shop[a].Sold || c > 1 {
+ return nil, errors.New("ib: invalid reservation")
+ }
+ s.state.Shop[a].Reserved = c == 1
+ return nil, nil
+ case "/IbShopRefresh":
+ cost := uint64(1)
+ if s.design.RefreshPriceUp > 0 {
+ cost += s.state.Play.Refreshes / s.design.RefreshPriceUp
+ }
+ if err := s.spend(cost); err != nil {
+ return nil, err
+ }
+ s.state.Play.Refreshes++
+ if err := s.refreshShop(true); err != nil {
+ return nil, err
+ }
+ out := s.shopWire()
+ out = wire.AppendVarint(out, 2, cost)
+ out = wire.AppendVarint(out, 3, s.state.Play.Coin)
+ return wire.AppendVarint(out, 4, s.state.Play.Refreshes), nil
+ case "/IbShopBuy":
+ if a >= uint64(len(s.state.Shop)) || s.state.Shop[a].Sold {
+ return nil, errors.New("ib: unavailable shop slot")
+ }
+ entry := &s.state.Shop[a]
+ if err := s.spend(entry.Price); err != nil {
+ return nil, err
+ }
+ i, err := s.addItem(entry.ID)
+ if err != nil {
+ return nil, err
+ }
+ entry.Sold = true
+ entry.Reserved = false
+ out := wire.AppendBytes(nil, 1, itemWire(i))
+ out = wire.AppendVarint(out, 2, entry.Price)
+ return wire.AppendVarint(out, 3, s.state.Play.Coin), nil
+ case "/IbItemSell":
+ i, ok := s.state.Items[a]
+ if !ok {
+ return nil, errors.New("ib: item not owned")
+ }
+ for _, p := range s.state.Deck {
+ if p.Index == a {
+ return nil, errors.New("ib: remove item from deck before sale")
+ }
+ }
+ price := uint64(math.RoundToEven(float64(s.design.Items[i.ID].Price) / 2))
+ if err := s.credit(price); err != nil {
+ return nil, err
+ }
+ delete(s.state.Items, a)
+ return scalars(a, price, s.state.Play.Coin), nil
+ case "/IbItemUpgrade":
+ i, ok := s.state.Items[a]
+ if !ok || c == 0 || c > math.MaxInt32 {
+ return nil, errors.New("ib: invalid upgrade")
+ }
+ d := s.design.Items[i.ID]
+ if i.Type == 1 && d.CostumeID != 0 {
+ if s.options.CostumeLevel == nil {
+ return nil, errors.New("ib: costume validation unavailable")
+ }
+ level, err := s.options.CostumeLevel(ctx, d.CostumeID)
+ if err != nil {
+ return nil, err
+ }
+ if i.Level+c > level {
+ return nil, errors.New("ib: upgrade exceeds owned costume level")
+ }
+ }
+ var total uint64
+ for n := range c {
+ cost, ok := s.design.UpgradeCosts[[3]uint64{i.Type, d.TypeID, i.Level + n + 2}]
+ if !ok || cost > math.MaxInt32-total {
+ return nil, errors.New("ib: level unavailable")
+ }
+ total += cost
+ }
+ if err := s.spend(total); err != nil {
+ return nil, err
+ }
+ i.Level += c
+ s.state.Items[a] = i
+ out := wire.AppendBytes(nil, 1, itemWire(i))
+ out = wire.AppendVarint(out, 2, total)
+ return wire.AppendVarint(out, 3, s.state.Play.Coin), nil
+ }
+ return nil, errors.New("ib: unsupported operation")
+}
+
+func (s *Service) end(ctx command.Context, result uint64) ([]byte, error) {
+ d, _, err := s.stage()
+ if err != nil {
+ return nil, err
+ }
+ if !s.state.Play.Entered || result < 1 || result > 3 {
+ return nil, errors.New("ib: no battle to settle")
+ }
+ s.state.Play.Entered = false
+ s.state.Process = nil
+ var gain, next, cleared, first uint64
+ var reward []byte
+ if result == 1 {
+ for n, stage := range d.Stages {
+ if stage.ID != s.state.Play.Stage {
+ continue
+ }
+ if n+1 < len(d.Stages) {
+ next = d.Stages[n+1].ID
+ gain = d.Stages[n+1].Credit
+ } else {
+ cleared = 1
+ }
+ break
+ }
+ if cleared == 1 && !s.state.Cleared[d.ID] {
+ first = 1
+ reward, err = s.economy.Apply(ctx, fmt.Sprintf("ib:%d:%d:%d", s.state.Season, d.ID, s.state.Run), nil, []gamedata.Reward{d.Reward})
+ if err != nil {
+ return nil, err
+ }
+ s.state.Cleared[d.ID] = true
+ }
+ } else {
+ s.state.Play.Life--
+ if s.state.Play.Life > 0 {
+ gain = s.design.RetryCredit
+ }
+ }
+ life := s.state.Play.Life
+ if cleared == 1 || life == 0 {
+ s.clearRun()
+ } else {
+ if next != 0 {
+ s.state.Play.Stage = next
+ }
+ if err = s.credit(gain); err != nil {
+ return nil, err
+ }
+ s.state.Play.Refreshes = 0
+ if err = s.refreshShop(true); err != nil {
+ return nil, err
+ }
+ }
+ out := scalars(0, cleared, first, life, next, gain, s.state.Play.Coin)
+ if len(reward) > 0 {
+ out = wire.AppendBytes(out, 1, reward)
+ }
+ return out, nil
+}
+
+func (s *Service) refreshShop(keepReserved bool) error {
+ _, stage, err := s.stage()
+ if err != nil {
+ return err
+ }
+ for slot := range uint64(4) {
+ if keepReserved && int(slot) < len(s.state.Shop) && s.state.Shop[slot].Reserved && !s.state.Shop[slot].Sold {
+ continue
+ }
+ id := stage.Slots[slot]
+ if id == 0 {
+ var pools [7][]uint64
+ for id, i := range s.design.Items {
+ if i.SellType == 1 && i.Grade < 7 {
+ pools[i.Grade] = append(pools[i.Grade], id)
+ }
+ }
+ var sum uint64
+ for grade, ids := range pools {
+ if len(ids) > 0 {
+ sum += stage.Ratios[grade]
+ }
+ }
+ draw, e := randomBelow(sum)
+ if e != nil {
+ return e
+ }
+ var chosen []uint64
+ for grade, ids := range pools {
+ if len(ids) == 0 {
+ continue
+ }
+ weight := stage.Ratios[grade]
+ if draw < weight {
+ chosen = ids
+ break
+ }
+ draw -= weight
+ }
+ slices.Sort(chosen)
+ index, e := randomBelow(uint64(len(chosen)))
+ if e != nil {
+ return e
+ }
+ id = chosen[index]
+ }
+ i, ok := s.design.Items[id]
+ if !ok {
+ return errors.New("ib: shop item unavailable")
+ }
+ entry := shopItem{Slot: slot, Type: i.Type, ID: id, Price: i.Price, Original: i.Price}
+ if len(s.state.Shop) <= int(slot) {
+ s.state.Shop = append(s.state.Shop, entry)
+ } else {
+ s.state.Shop[slot] = entry
+ }
+ }
+ return nil
+}
+
+func rotate(p gamedata.IBPoint, r uint64) gamedata.IBPoint {
+ switch r {
+ case 1:
+ return gamedata.IBPoint{X: -p.Y, Y: p.X}
+ case 2:
+ return gamedata.IBPoint{X: -p.X, Y: -p.Y}
+ case 3:
+ return gamedata.IBPoint{X: p.Y, Y: -p.X}
+ }
+ return p
+}
+func cells(shape []gamedata.IBPoint, p placement) ([]gamedata.IBPoint, error) {
+ if p.Position >= 49 || p.Rotation > 3 {
+ return nil, errors.New("ib: invalid placement")
+ }
+ if len(shape) == 0 {
+ shape = []gamedata.IBPoint{{}}
+ }
+ var out []gamedata.IBPoint
+ for _, offset := range shape {
+ point := rotate(offset, p.Rotation)
+ point.X += int(p.Position % 7)
+ point.Y += int(p.Position / 7)
+ if point.X < 0 || point.X >= 7 || point.Y < 0 || point.Y >= 7 {
+ return nil, errors.New("ib: item outside board")
+ }
+ out = append(out, point)
+ }
+ return out, nil
+}
+func (s *Service) validateDeck(deck []placement) error {
+ if len(deck) > len(s.state.Items) {
+ return errors.New("ib: too many deployed items")
+ }
+ seen := map[uint64]bool{}
+ floors := map[gamedata.IBPoint]bool{}
+ sockets := map[gamedata.IBPoint]bool{}
+ for _, p := range deck {
+ if _, ok := s.state.Items[p.Index]; !ok || seen[p.Index] {
+ return errors.New("ib: invalid item reference")
+ }
+ seen[p.Index] = true
+ }
+ for typ := range uint64(3) {
+ occupied := map[gamedata.IBPoint]bool{}
+ for _, p := range deck {
+ i := s.state.Items[p.Index]
+ if i.Type != typ {
+ continue
+ }
+ d := s.design.Items[i.ID]
+ points, err := cells(d.Shape, p)
+ if err != nil {
+ return err
+ }
+ if typ == 2 {
+ point := gamedata.IBPoint{X: int(p.Position % 7), Y: int(p.Position / 7)}
+ if !sockets[point] || occupied[point] {
+ return errors.New("ib: equipment requires free unit socket")
+ }
+ occupied[point] = true
+ continue
+ }
+ for _, point := range points {
+ if occupied[point] || typ == 1 && !floors[point] {
+ return errors.New("ib: overlapping item or missing floor")
+ }
+ occupied[point] = true
+ if typ == 0 {
+ floors[point] = true
+ }
+ }
+ if typ == 1 {
+ for _, offset := range s.design.Sockets[[2]uint64{d.TypeID, i.Level + 1}] {
+ if offset == (gamedata.IBPoint{}) || !slices.Contains(d.Shape, offset) {
+ continue
+ }
+ point := rotate(offset, p.Rotation)
+ point.X += int(p.Position % 7)
+ point.Y += int(p.Position / 7)
+ sockets[point] = true
+ }
+ }
+ }
+ }
+ return nil
+}
diff --git a/go/internal/server/domain/battle/ib/service_test.go b/go/internal/server/domain/battle/ib/service_test.go
new file mode 100644
index 0000000..2d76b46
--- /dev/null
+++ b/go/internal/server/domain/battle/ib/service_test.go
@@ -0,0 +1,413 @@
+//go:build integration
+
+package ib
+
+import (
+ "bytes"
+ "encoding/base64"
+ "fmt"
+ "slices"
+ "testing"
+
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+type ledger struct {
+ grants []gamedata.Reward
+ fail bool
+}
+
+func (l *ledger) Apply(_ command.Context, _ string, _ []gamedata.Reward, rewards []gamedata.Reward) ([]byte, error) {
+ if l.fail {
+ return nil, fmt.Errorf("reward storage unavailable")
+ }
+ l.grants = append(l.grants, rewards...)
+ return []byte{8, 1}, nil
+}
+func liveDesign(t *testing.T) *gamedata.IBDesign {
+ t.Helper()
+ versions, err := versionconfig.Find()
+ if err != nil {
+ t.Fatal(err)
+ }
+ versionconfig.Use(versions)
+ d, err := gamedata.LoadIBDesign(versions.Resolve("data/resources/GameData"), versions.GameDataVersion)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return d
+}
+func messages(t *testing.T, b []byte, field int) [][]byte {
+ t.Helper()
+ var out [][]byte
+ if err := wire.Walk(b, func(f wire.Field) error {
+ if f.Number == field && f.Type == 2 {
+ out = append(out, slices.Clone(f.Value))
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+
+func assertReservedOffer(t *testing.T, response, expected []byte) {
+ t.Helper()
+ var matches [][]byte
+ for _, entry := range messages(t, response, 1) {
+ if value(entry, 1) == value(expected, 1) {
+ matches = append(matches, entry)
+ }
+ }
+ if len(matches) != 1 {
+ t.Fatalf("reserved slot occurred %d times, want exactly one", len(matches))
+ }
+ entry := matches[0]
+ if value(entry, 3) != value(expected, 3) || value(entry, 4) != value(expected, 4) || value(entry, 7) != 1 {
+ t.Fatal("reservation lost its item, price, or reserved flag")
+ }
+}
+
+// LocalTextTable 7900025/26/84 and 7900122/23/29 (queried with gamedata_db.py,
+// 20261012190548) define loss retries, one first-clear reward, run inventory,
+// post-battle shop refresh, and reservations. Request/response fields and base64
+// process payload are independently specified by 2.36.7 Proto.Net and IBPacket.
+func TestBoardLifecyclePreservesBattleReservationAndFirstClear(t *testing.T) {
+ d := liveDesign(t)
+ store := stateio.NewMemory()
+ ctx := command.Context{Identity: command.Identity{SessionID: "ib-lifecycle"}, State: store}
+ money := &ledger{}
+ seasons := make([]uint64, 0, len(d.Seasons))
+ for season := range d.Seasons {
+ seasons = append(seasons, season)
+ }
+ slices.Sort(seasons)
+ period := Period{Season: seasons[0], Regular: seasons[0], Open: true}
+ open := func() *Service {
+ t.Helper()
+ s, e := Open(ctx, stateio.RootStore{}, d, money, Options{Period: func(command.Context) (Period, error) { return period, nil }})
+ if e != nil {
+ t.Fatal(e)
+ }
+ return s
+ }
+ s := open()
+ var sequence uint64
+ call := func(path string, args ...uint64) ([]byte, error) {
+ sequence++
+ b := wire.AppendVarint(nil, 1, sequence)
+ for n, v := range args {
+ b = wire.AppendVarint(b, n+2, v)
+ }
+ _, out, handled, e := s.Handle(ctx, path, b)
+ if !handled {
+ t.Fatalf("unhandled %s", path)
+ }
+ return out, e
+ }
+ must := func(path string, args ...uint64) []byte {
+ t.Helper()
+ out, e := call(path, args...)
+ if e != nil {
+ t.Fatalf("%s: %v", path, e)
+ }
+ return out
+ }
+ var dungeon gamedata.IBDungeon
+ for _, id := range d.Seasons[period.Season] {
+ if candidate := d.Dungeons[id]; candidate.Unlock == 0 {
+ dungeon = candidate
+ break
+ }
+ }
+ if dungeon.ID == 0 {
+ t.Fatal("no initial board in selected season")
+ }
+ if _, e := call("/IbStageEnd", 1); e == nil {
+ t.Fatal("settled without starting a battle")
+ }
+ entered := must("/IbDungeonEnter", dungeon.ID)
+ playInfo := messages(t, entered, 1)[0]
+ if value(playInfo, 3) != dungeon.Life || len(messages(t, entered, 2)) != len(d.Decks[d.StartDeck]) {
+ t.Fatal("entry did not install authored starting board")
+ }
+ for _, id := range d.Seasons[period.Season] {
+ if d.Dungeons[id].Unlock == dungeon.ID {
+ must("/IbDungeonGiveUp")
+ if _, e := call("/IbDungeonEnter", id); e == nil {
+ t.Fatal("locked successor board entered without clear")
+ }
+ must("/IbDungeonEnter", dungeon.ID)
+ break
+ }
+ }
+ shop := messages(t, must("/IbShopInfo"), 1)
+ reserved := slices.Clone(shop[0])
+ slot := value(reserved, 1)
+ must("/IbShopItemReserve", slot, 1)
+ before := s.state.Play.Coin
+ refreshed := must("/IbShopRefresh")
+ if value(refreshed, 2) == 0 || value(refreshed, 3) >= before {
+ t.Fatal("shop refresh did not consume local tokens")
+ }
+ assertReservedOffer(t, refreshed, reserved)
+ s = open()
+ start := must("/IbStageStart", dungeon.ID, dungeon.Stages[0].ID)
+ encoded := messages(t, start, 1)[0]
+ process, e := base64.StdEncoding.DecodeString(string(encoded))
+ if e != nil {
+ t.Fatal(e)
+ }
+ if value(process, 2) == 0 || value(process, 3) != dungeon.ID || len(messages(t, process, 7)) == 0 || len(messages(t, process, 8)) == 0 {
+ t.Fatal("battle process omitted seeded authored opponent")
+ }
+ s = open()
+ if resumed := must("/IbStageStart", dungeon.ID, dungeon.Stages[0].ID); !bytes.Equal(resumed, start) {
+ t.Fatal("reconnect changed battle seed or decks")
+ }
+ if _, e := call("/IbShopBuy", slot); e == nil {
+ t.Fatal("changed inventory while persisted battle was active")
+ }
+ lost := must("/IbStageEnd", 2)
+ if value(lost, 4) != dungeon.Life-1 || value(lost, 5) != 0 {
+ t.Fatal("defeat advanced stage or failed to consume retry")
+ }
+ s = open()
+ assertReservedOffer(t, must("/IbShopInfo"), reserved)
+ for n, stage := range dungeon.Stages {
+ must("/IbStageStart", dungeon.ID, stage.ID)
+ if n == len(dungeon.Stages)-1 {
+ money.fail = true
+ if _, e := call("/IbStageEnd", 1); e == nil {
+ t.Fatal("failed reward grant committed clear")
+ }
+ money.fail = false
+ s = open()
+ }
+ out := must("/IbStageEnd", 1)
+ if n+1 < len(dungeon.Stages) {
+ if value(out, 5) != dungeon.Stages[n+1].ID {
+ t.Fatal("victory did not unlock next stage")
+ }
+ } else if value(out, 2) != 1 || value(out, 3) != 1 {
+ t.Fatal("final victory was not marked first clear")
+ }
+ s = open()
+ }
+ if len(money.grants) != 1 || money.grants[0] != dungeon.Reward {
+ t.Fatal("first clear did not grant the authored board reward exactly once")
+ }
+ if len(messages(t, must("/IbItemInfo"), 1)) != 0 || len(messages(t, must("/IbDeckInfo"), 1)) != 0 {
+ t.Fatal("completed board retained inventory or deployed units")
+ }
+ for _, id := range d.Seasons[period.Season] {
+ if d.Dungeons[id].Unlock == dungeon.ID {
+ must("/IbDungeonEnter", id)
+ must("/IbDungeonGiveUp")
+ break
+ }
+ }
+ must("/IbDungeonEnter", dungeon.ID)
+ for _, stage := range dungeon.Stages {
+ must("/IbStageStart", dungeon.ID, stage.ID)
+ must("/IbStageEnd", 1)
+ }
+ if len(money.grants) != 1 {
+ t.Fatal("rechallenge paid the first-clear reward twice")
+ }
+ if len(seasons) > 1 {
+ period.Season = seasons[1]
+ out := must("/IbMainInfo")
+ if value(out, 2) != 1 || s.state.Cleared[dungeon.ID] {
+ t.Fatal("season transition preserved old first-clear flags")
+ }
+ s = open()
+ }
+ period.Open = false
+ if _, e := call("/IbDungeonEnter", d.Seasons[period.Season][0]); e == nil {
+ t.Fatal("entered a board outside its season window")
+ }
+}
+
+func TestInventoryPurchasesUpgradeReplayAndDeckValidation(t *testing.T) {
+ d := liveDesign(t)
+ store := stateio.NewMemory()
+ ctx := command.Context{Identity: command.Identity{SessionID: "ib-inventory"}, State: store}
+ var season, id uint64
+ for se, ids := range d.Seasons {
+ for _, candidate := range ids {
+ if d.Dungeons[candidate].Unlock == 0 {
+ season, id = se, candidate
+ break
+ }
+ }
+ if id != 0 {
+ break
+ }
+ }
+ ownedLevels := map[uint64]uint64{}
+ open := func() *Service {
+ t.Helper()
+ s, e := Open(ctx, stateio.RootStore{}, d, &ledger{}, Options{CostumeLevel: func(_ command.Context, id uint64) (uint64, error) { return ownedLevels[id], nil }, Period: func(command.Context) (Period, error) { return Period{Season: season, Open: true}, nil }})
+ if e != nil {
+ t.Fatal(e)
+ }
+ return s
+ }
+ s := open()
+ seq := uint64(0)
+ call := func(path string, body []byte) ([]byte, error) {
+ seq++
+ body = append(wire.AppendVarint(nil, 1, seq), body...)
+ _, out, _, e := s.Handle(ctx, path, body)
+ return out, e
+ }
+ if _, e := call("/IbDungeonEnter", wire.AppendVarint(nil, 2, id)); e != nil {
+ t.Fatal(e)
+ }
+ var unit, floor item
+ for _, i := range s.state.Items {
+ if i.Type == 1 {
+ unit = i
+ }
+ if i.Type == 0 {
+ floor = i
+ }
+ }
+ if unit.Index == 0 || floor.Index == 0 || len(s.state.Items) < 3 {
+ t.Fatal("starting inventory cannot construct the formation scenarios")
+ }
+ if !slices.Equal(d.Items[unit.ID].Shape, []gamedata.IBPoint{{X: 0, Y: 0}, {X: 1, Y: 0}}) || !slices.Equal(d.Items[floor.ID].Shape, []gamedata.IBPoint{{X: 0, Y: 0}, {X: 1, Y: 0}, {X: 0, Y: 1}, {X: 1, Y: 1}}) {
+ t.Fatal("formation scenarios require a horizontal two-cell unit and a two-by-two floor")
+ }
+ originalDeck := slices.Clone(s.state.Deck)
+ invalid := wire.AppendBytes(nil, 2, scalars(unit.Index, 0, 0))
+ if _, e := call("/IbDeckSave", invalid); e == nil {
+ t.Fatal("accepted unit without supporting floor")
+ }
+ if !slices.Equal(originalDeck, s.state.Deck) {
+ t.Fatal("rejected formation modified deployed board")
+ }
+ var valid []byte
+ for _, p := range originalDeck {
+ valid = wire.AppendBytes(valid, 2, deckWire(p))
+ }
+ if _, e := call("/IbDeckSave", valid); e != nil {
+ t.Fatal(e)
+ }
+ s = open()
+ if !slices.Equal(originalDeck, s.state.Deck) {
+ t.Fatal("saved formation did not survive reconnect")
+ }
+ duplicate := wire.AppendBytes(nil, 2, scalars(floor.Index, 0, 0))
+ duplicate = wire.AppendBytes(duplicate, 2, scalars(unit.Index, 0, 0))
+ duplicate = wire.AppendBytes(duplicate, 2, scalars(unit.Index, 7, 0))
+ if _, e := call("/IbDeckSave", duplicate); e == nil {
+ t.Fatal("same inventory item was deployed twice")
+ }
+ if !slices.Equal(originalDeck, s.state.Deck) {
+ t.Fatal("rejected duplicate reference modified the saved formation")
+ }
+ price, canUpgrade := d.UpgradeCosts[[3]uint64{unit.Type, d.Items[unit.ID].TypeID, 2}]
+ if !canUpgrade || price == 0 || price > s.state.Play.Coin {
+ t.Fatal("selected starting unit has no affordable next-grade enhancement")
+ }
+ {
+ body := wire.AppendVarint(nil, 2, unit.Index)
+ body = wire.AppendVarint(body, 3, 1)
+ if _, e := call("/IbItemUpgrade", body); e == nil {
+ t.Fatal("unowned costume bypassed the enhancement limit")
+ }
+ ownedLevels[d.Items[unit.ID].CostumeID] = 1
+ seq++
+ request := append(wire.AppendVarint(nil, 1, seq), body...)
+ before := s.state.Play.Coin
+ _, up, _, e := s.Handle(ctx, "/IbItemUpgrade", request)
+ if e != nil {
+ t.Fatal(e)
+ }
+ s = open()
+ _, again, _, e := s.Handle(ctx, "/IbItemUpgrade", request)
+ if e != nil || !bytes.Equal(up, again) || s.state.Play.Coin != before-price || s.state.Items[unit.Index].Level != 1 {
+ t.Fatal("upgrade replay changed level or paid twice")
+ }
+ if _, e := call("/IbItemUpgrade", body); e == nil {
+ t.Fatal("enhanced beyond the owned costume's enhancement")
+ }
+ }
+ shop, err := call("/IbShopInfo", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var offer []byte
+ for _, r := range messages(t, shop, 1) {
+ if value(r, 4) <= s.state.Play.Coin {
+ offer = r
+ break
+ }
+ }
+ if offer == nil {
+ t.Fatal("no affordable initial offer")
+ }
+ seq++
+ request := wire.AppendVarint(nil, 1, seq)
+ request = wire.AppendVarint(request, 2, value(offer, 1))
+ before := s.state.Play.Coin
+ _, bought, _, err := s.Handle(ctx, "/IbShopBuy", request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ purchased := messages(t, bought, 1)[0]
+ index := value(purchased, 1)
+ s = open()
+ _, replay, _, err := s.Handle(ctx, "/IbShopBuy", request)
+ if err != nil || !bytes.Equal(bought, replay) || s.state.Play.Coin != before-value(offer, 4) {
+ t.Fatal("purchase replay duplicated debit")
+ }
+ if _, err = call("/IbShopBuy", wire.AppendVarint(nil, 2, value(offer, 1))); err == nil {
+ t.Fatal("sold slot sold again with another sequence")
+ }
+ if _, err = call("/IbItemSell", wire.AppendVarint(nil, 2, index)); err != nil {
+ t.Fatal(err)
+ }
+ s = open()
+ if _, exists := s.state.Items[index]; exists {
+ t.Fatal("sold item reappeared after restore")
+ }
+ if _, err = call("/IbItemSell", wire.AppendVarint(nil, 2, index)); err == nil {
+ t.Fatal("sold item produced more tokens")
+ }
+ if _, err = call("/IbDungeonGiveUp", nil); err != nil {
+ t.Fatal(err)
+ }
+ s = open()
+ if len(s.state.Items) != 0 || len(s.state.Deck) != 0 || s.state.Play.Dungeon != 0 {
+ t.Fatal("give-up survived restore as an active run")
+ }
+ if _, e := call("/IbDungeonEnter", wire.AppendVarint(nil, 2, id)); e != nil {
+ t.Fatal(e)
+ }
+ board := d.Dungeons[id]
+ for attempt := uint64(0); attempt < board.Life; attempt++ {
+ args := wire.AppendVarint(nil, 2, id)
+ args = wire.AppendVarint(args, 3, board.Stages[0].ID)
+ if _, e := call("/IbStageStart", args); e != nil {
+ t.Fatal(e)
+ }
+ out, e := call("/IbStageEnd", wire.AppendVarint(nil, 2, 2))
+ if e != nil {
+ t.Fatal(e)
+ }
+ if value(out, 4) != board.Life-attempt-1 {
+ t.Fatal("loss consumed incorrect challenge count")
+ }
+ s = open()
+ }
+ if s.state.Play.Dungeon != 0 || len(s.state.Items) != 0 {
+ t.Fatal("exhausted challenges left a resumable board")
+ }
+}
diff --git a/go/internal/server/domain/battle/monsterhunt/protocol_adapter.go b/go/internal/server/domain/battle/monsterhunt/protocol_adapter.go
index f5272ed..587b67c 100644
--- a/go/internal/server/domain/battle/monsterhunt/protocol_adapter.go
+++ b/go/internal/server/domain/battle/monsterhunt/protocol_adapter.go
@@ -382,7 +382,7 @@ func (s *Service) encodeUser(u user, c Season, level uint64) []byte {
b = wire.AppendVarint(b, n, v)
}
}
- if u.Played && !u.Claimed && uint64(s.now().UnixMilli()) > c.Calculate {
+ if _, pending := s.pendingSeasonReward(); pending {
b = wire.AppendVarint(b, 10, 1)
}
return b
@@ -462,6 +462,11 @@ func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []b
return s.scheduleInfo(ctx, req)
}
c := s.current()
+ if path == "/MonsterHuntSeasonReward" {
+ if pending, ok := s.pendingSeasonReward(); ok {
+ c = pending
+ }
+ }
u, e := s.getUser(c)
if e != nil {
return code, nil, true, e
@@ -475,8 +480,12 @@ func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []b
case "/MonsterHuntUserInfo":
out = wire.AppendBytes(nil, 1, s.encodeUser(u, c, u.ClearLevel))
if u.Played {
- out = wire.AppendVarint(out, 2, 1)
- out = wire.AppendDouble(out, 3, 100)
+ rank, rankErr := s.ranking(u)
+ if rankErr != nil {
+ return code, nil, true, rankErr
+ }
+ out = wire.AppendVarint(out, 2, rank.Rank)
+ out = wire.AppendDouble(out, 3, rank.TopPercent)
}
case "/MonsterHuntDeckInfo":
for _, v := range s.state.Decks {
@@ -694,11 +703,15 @@ func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []b
u.DailyDate = uint64(s.now().UnixMilli())
next.Users[strconv.FormatUint(c.ID, 10)] = u
out = wire.AppendBytes(out, 1, s.encodeUser(u, c, u.ClearLevel))
- out = wire.AppendVarint(out, 4, 1)
- out = wire.AppendDouble(out, 5, 100)
+ rank, rankErr := s.ranking(u)
+ if rankErr != nil {
+ return code, nil, true, rankErr
+ }
+ out = wire.AppendVarint(out, 4, rank.Rank)
+ out = wire.AppendDouble(out, 5, rank.TopPercent)
mutation = true
case "/MonsterHuntSeasonReward":
- if !u.Played || u.Claimed || uint64(s.now().UnixMilli()) <= c.Calculate {
+ if !u.Played || u.RankLevel == 0 || u.Claimed || uint64(s.now().UnixMilli()) < c.End || uint64(s.now().UnixMilli()) <= c.Calculate {
e = fmt.Errorf("monsterhunt: season reward unavailable")
break
}
@@ -708,7 +721,11 @@ func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []b
e = loadErr
break
}
- rewards := s.rankRewards(d, c.RankGroup)
+ rank, rankErr := s.ranking(u)
+ if rankErr != nil {
+ return code, nil, true, rankErr
+ }
+ rewards := s.rankRewards(d, c.RankGroup, rank)
bundle, grantErr := s.grant(ctx, "monsterhunt:"+key, rewards)
if grantErr != nil {
e = grantErr
@@ -717,14 +734,14 @@ func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []b
next.Users[strconv.FormatUint(c.ID, 10)] = u
out = wire.AppendVarint(nil, 3, u.Hunt)
out = wire.AppendBytes(out, 4, bundle)
- out = wire.AppendVarint(out, 1, 1)
+ out = wire.AppendVarint(out, 1, rank.Rank)
score, scoreErr := s.score(u)
if scoreErr != nil {
e = scoreErr
break
}
out = wire.AppendDouble(out, 2, score)
- out = wire.AppendDouble(out, 5, 100)
+ out = wire.AppendDouble(out, 5, rank.TopPercent)
mutation = true
}
if e != nil {
@@ -1002,8 +1019,12 @@ func (s *Service) CompleteBattle(ctx command.Context, req []byte, receipt string
u.DailyDamage = damage
}
out, _, _ = wire.ReplaceBytes(out, 13, s.encodeUser(u, c, u.ClearLevel))
- out = wire.AppendVarint(out, 14, 1)
- out = wire.AppendDouble(out, 26, 100)
+ rank, rankErr := s.ranking(u)
+ if rankErr != nil {
+ return nil, rankErr
+ }
+ out = wire.AppendVarint(out, 14, rank.Rank)
+ out = wire.AppendDouble(out, 26, rank.TopPercent)
next := s.clone()
next.Users[strconv.FormatUint(c.ID, 10)] = u
next.Replies[key] = reply{append([]byte(nil), req...), out}
diff --git a/go/internal/server/domain/battle/monsterhunt/rewards.go b/go/internal/server/domain/battle/monsterhunt/rewards.go
index cff7359..dd8c16a 100644
--- a/go/internal/server/domain/battle/monsterhunt/rewards.go
+++ b/go/internal/server/domain/battle/monsterhunt/rewards.go
@@ -81,14 +81,11 @@ func monsterHuntAttackDamage(request []byte) (uint64, error) {
return total, nil
}
-func (s *Service) rankRewards(d *gamedata.MonsterHunt, group uint64) []gamedata.BattleReward {
+func (s *Service) rankRewards(d *gamedata.MonsterHunt, group uint64, rank RankEntry) []gamedata.BattleReward {
var selected *gamedata.MonsterHuntRankReward
for _, r := range d.Ranks[group] {
- threshold := float64(1)
- if r.Type == 1 {
- threshold = 100
- }
- if r.Ranking >= threshold && (selected == nil || r.Type < selected.Type || r.Type == selected.Type && r.Ranking < selected.Ranking) {
+ eligible := r.Type == 0 && float64(rank.Rank) <= r.Ranking || r.Type == 1 && rank.TopPercent < r.Ranking+0.1
+ if rank.Rank != 0 && eligible && (selected == nil || r.Type < selected.Type || r.Type == selected.Type && r.Ranking < selected.Ranking) {
selected = &r
}
}
@@ -97,3 +94,18 @@ func (s *Service) rankRewards(d *gamedata.MonsterHunt, group uint64) []gamedata.
}
return selected.Rewards
}
+
+func (s *Service) pendingSeasonReward() (Season, bool) {
+ var next Season
+ now := uint64(s.now().UnixMilli())
+ for _, season := range s.seasons {
+ u, ok := s.state.Users[fmt.Sprint(season.ID)]
+ if !ok || !u.Played || u.RankLevel == 0 || u.Claimed || now < season.End || now <= season.Calculate {
+ continue
+ }
+ if next.ID == 0 || season.Calculate < next.Calculate || season.Calculate == next.Calculate && season.ID < next.ID {
+ next = season
+ }
+ }
+ return next, next.ID != 0
+}
diff --git a/go/internal/server/domain/battle/protocol_adapter.go b/go/internal/server/domain/battle/protocol_adapter.go
index a180fa5..aa060ca 100644
--- a/go/internal/server/domain/battle/protocol_adapter.go
+++ b/go/internal/server/domain/battle/protocol_adapter.go
@@ -283,6 +283,15 @@ func (s *Service) handle(ctx command.Context, path string, request []byte) (int,
if len(state.Phases) != 0 && Index != state.Phases[state.Phase].DeckID {
return 0, nil, true, errors.New("battle: start Index does not match current Phase")
}
+ if runtime := s.eventBattle(state.Mode); runtime != nil {
+ if validator, ok := runtime.(interface {
+ ValidateBattleStart(command.Context, []byte) error
+ }); ok {
+ if err := validator.ValidateBattleStart(ctx, request); err != nil {
+ return 0, nil, true, err
+ }
+ }
+ }
nextRound := state.Round + 1
if nextRound == 1 && gamedata.IsSkyWayMode(state.Mode) {
if err := s.skyway.SkyWayBattleStarted(ctx, state.Mode, state.EnterReceipt); err != nil {
diff --git a/go/internal/server/domain/battle/pvp/contracts.go b/go/internal/server/domain/battle/pvp/contracts.go
index 01250d5..ee18b2e 100644
--- a/go/internal/server/domain/battle/pvp/contracts.go
+++ b/go/internal/server/domain/battle/pvp/contracts.go
@@ -123,6 +123,11 @@ type DefensePublished struct {
Version int
Defense PublishedSnapshot
}
+
+type PopularityPublished struct {
+ Timestamp, Side uint64
+ Snapshot PublishedSnapshot
+}
type BattleSettled struct {
Seeds []uint64
Version int
diff --git a/go/internal/server/domain/battle/pvp/protocol_adapter.go b/go/internal/server/domain/battle/pvp/protocol_adapter.go
index 00b3623..c22f5a3 100644
--- a/go/internal/server/domain/battle/pvp/protocol_adapter.go
+++ b/go/internal/server/domain/battle/pvp/protocol_adapter.go
@@ -16,6 +16,7 @@ import (
)
var codes = map[string]int{
+ "/ColosseumPromotionRewardInfo": 0,
"/PvpBattleReplayInfo": 0, "/PvpBattleReset": 0,
"/PvpBattleUserInfo": 86, "/PvpBattleDeckInfo": 87, "/PvpBattleDeckSave": 88, "/PvpBattleMatching": 89, "/PvpBattleStart": 90, "/PvpBattleEnd": 91, "/PvpBattleReward": 92, "/PvpBattleRanking": 93, "/PvpBattleRankUserDetail": 94, "/PvpBattleHistory": 97, "/PvpBattleHistoryDeckInfo": 98, "/PvpSeasonReward": 136, "/PvpBattleOnceRewardInfo": 277, "/PvpContentsItemRenew": 401,
"/ColosseumUserInfo": 473, "/ColosseumSeasonReward": 474, "/ColosseumDeckInfo": 475, "/ColosseumDeckSave": 476, "/ColosseumContentsItemRenew": 478, "/ColosseumRanking": 479, "/ColosseumRankDetail": 480, "/ColosseumBattleHistory": 481, "/ColosseumBattleReplayInfo": 482, "/ColosseumBattleMatching": 483, "/ColosseumBattleStart": 484, "/ColosseumBattleEnd": 485, "/ColosseumBlessInfo": 486, "/ColosseumBlessSave": 487, "/ColosseumBattleCountReset": 488, "/ColosseumApBuy": 489,
@@ -86,6 +87,9 @@ func (s *Service) handle(ctx command.Context, mode Mode, path string, request []
}
m := s.state.Modes[mode]
switch path {
+ case "/ColosseumPromotionRewardInfo":
+ // Current Colosseum design has season rewards only; the native client discards this legacy query's list.
+ return nil, nil
case "/PvpBattleUserInfo", "/ColosseumUserInfo":
return s.userInfo(ctx, mode)
case "/PvpBattleDeckInfo":
diff --git a/go/internal/server/domain/battle/pvp/service.go b/go/internal/server/domain/battle/pvp/service.go
index c36f0dd..47b9184 100644
--- a/go/internal/server/domain/battle/pvp/service.go
+++ b/go/internal/server/domain/battle/pvp/service.go
@@ -362,6 +362,19 @@ func (s *Service) saveFormation(ctx command.Context, mode Mode, side uint64, dec
return e
}
}
+ if mode == Mirror {
+ progress, e := s.progress(mode, season.ID)
+ if e != nil {
+ return e
+ }
+ own, e := s.own(mode, season.ID, next, progress)
+ if e != nil {
+ return e
+ }
+ if e = publish(ctx, fmt.Sprintf("pvp:%s:%d:popularity:%d:%d", s.profile.OwnerID, season.ID, side, next.Version), "pvp.popularity", PopularityPublished{Timestamp: uint64(s.now().UnixMilli()), Side: side, Snapshot: own}); e != nil {
+ return e
+ }
+ }
return s.save(ctx)
}
func (s *Service) validateDeck(mode Mode, season uint64, deck [][]byte) error {
diff --git a/go/internal/server/domain/battle/roguelike/battle.go b/go/internal/server/domain/battle/roguelike/battle.go
new file mode 100644
index 0000000..18b9607
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/battle.go
@@ -0,0 +1,288 @@
+package roguelike
+
+import (
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "fmt"
+ "math"
+)
+
+func (s *Service) HandlesBattle(mode uint64) bool { return mode == 21 || mode == 27 }
+func (s *Service) battleRule(r *run) (uint64, uint64) {
+ if r.State == 9 {
+ rule := s.design.Rooms.Row(s.design.Default.V(19), s.design.Default.V(20))
+ return rule.V(1), 27
+ }
+ _, rule := s.current(r)
+ return rule.V(1), 21
+}
+func (s *Service) EnterBattle(ctx command.Context, b []byte, key string) ([]byte, error) {
+ v, p, e := s.load(ctx)
+ if e != nil {
+ return nil, e
+ }
+ r := v.Run
+ if !p.Active || r == nil || r.State != 3 && r.State != 9 || r.Encounter != "" {
+ return nil, fail("no eligible battle room")
+ }
+ deck, mode := s.battleRule(r)
+ if n(b, 4) != deck || n(b, 5) != mode || n(b, 3) != 0 {
+ return nil, fail("battle does not match selected room")
+ }
+ if len(r.Deck) == 0 {
+ return nil, fail("formation not saved")
+ }
+ r.ChangedParticipants = nil
+ r.Encounter = key
+ r.EncounterMode = mode
+ return nil, s.save(ctx, v)
+}
+func (s *Service) ValidateBattleStart(ctx command.Context, b []byte) error {
+ v, _, e := s.load(ctx)
+ if e != nil {
+ return e
+ }
+ r := v.Run
+ if r == nil || r.Encounter == "" || s.options.Evidence == nil {
+ return fail("no encounter")
+ }
+ proof := s.options.Evidence(ctx)
+ if proof.Receipt != r.Encounter {
+ return fail("battle receipt mismatch")
+ }
+ if proof.Round > 0 {
+ return nil
+ }
+ blue, e := messages(b, 5)
+ if e != nil {
+ return e
+ }
+ expected := map[uint64][]byte{}
+ for _, d := range r.Deck {
+ if int64(n(d, 2)) >= 0 {
+ expected[n(d, 1)] = d
+ }
+ }
+ if len(blue) != len(expected) || len(blue) == 0 || len(blue) > 5 {
+ return fail("battle party differs from formation")
+ }
+ seen := map[uint64]bool{}
+ unique := map[uint64]bool{}
+ for _, a := range blue {
+ index := n(a, 2)
+ d, ok := expected[index]
+ if !ok || seen[index] || n(a, 1) == 0 || unique[n(a, 1)] {
+ return fail("invalid battle character")
+ }
+ seen[index] = true
+ unique[n(a, 1)] = true
+ var c *character
+ for i := range r.Characters {
+ if r.Characters[i].Index == index {
+ c = &r.Characters[i]
+ }
+ }
+ if c == nil || c.HP == 0 || n(a, 3) != c.ID || n(a, 4) != c.HP || n(a, 5) != s.design.Default.V(7) || n(a, 9) != n(d, 2) {
+ return fail("battle character differs from run")
+ }
+ valid := false
+ for _, costume := range r.Costumes {
+ if costume.Character == c.Index && n(a, 6) == costume.Index && n(a, 7) == costume.ID && n(a, 8) == costume.Level {
+ valid = true
+ }
+ }
+ if !valid {
+ return fail("battle costume unowned")
+ }
+ if n(a, 12) != 0 {
+ return fail("roguelike equipment unavailable")
+ }
+ }
+ deck, _ := s.battleRule(r)
+ red, e := messages(b, 4)
+ if e != nil {
+ return e
+ }
+ want := s.design.Enemies[deck]
+ if len(red) != len(want) {
+ return fail("enemy party differs from GameData")
+ }
+ for i, a := range red {
+ enemy := want[i]
+ if n(a, 1) == 0 || unique[n(a, 1)] || n(a, 2) != 0 || n(a, 3) != enemy.ID || n(a, 5) != enemy.Level || n(a, 9) != enemy.Position || n(a, 4) == 0 {
+ return fail("invalid enemy party")
+ }
+ unique[n(a, 1)] = true
+ }
+ return nil
+}
+func (s *Service) preview(ctx command.Context, v *state, b []byte) ([]byte, error) {
+ r := v.Run
+ if r.Encounter == "" || s.options.Evidence == nil {
+ return nil, fail("preview without battle")
+ }
+ proof := s.options.Evidence(ctx)
+ result, damage := n(b, 2), n(b, 3)
+ if proof.Receipt != r.Encounter || proof.Round == 0 || result == 0 || result > 4 || damage > math.MaxInt64 {
+ return nil, fail("invalid battle preview")
+ }
+ out := wire.AppendVarint(nil, 1, result)
+ if r.State == 9 {
+ out = wire.AppendVarint(out, 4, damage)
+ } else if result == 1 {
+ _, room := s.current(r)
+ out = wire.AppendVarint(out, 3, uint64(float64(room.V(3))*s.design.Levels.Row(0, r.Level).D(5)))
+ }
+ return out, nil
+}
+func (s *Service) CompleteBattle(ctx command.Context, b []byte, key string) ([]byte, error) {
+ v, p, e := s.load(ctx)
+ if e != nil {
+ return nil, e
+ }
+ r := v.Run
+ if !p.Active || r == nil || r.Encounter != key || s.options.Evidence == nil {
+ return nil, fail("settlement without encounter")
+ }
+ proof := s.options.Evidence(ctx)
+ deck, mode := s.battleRule(r)
+ if proof.Receipt != key || proof.Mode != mode || proof.Deck != deck || proof.Round == 0 || len(proof.InitialBlue) == 0 {
+ return nil, fail("settlement before started battle")
+ }
+ result := n(b, 2)
+ if result == 0 || result > 4 {
+ return nil, fail("invalid result")
+ }
+ chars, e := messages(b, 3)
+ if e != nil {
+ return nil, e
+ }
+ participants := map[uint64]bool{}
+ for _, a := range proof.InitialBlue {
+ participants[n(a, 2)] = true
+ }
+ for _, index := range r.ChangedParticipants {
+ participants[index] = true
+ }
+ seen := map[uint64]bool{}
+ var out []byte
+ for _, raw := range chars {
+ index := n(raw, 1)
+ if !participants[index] || seen[index] {
+ return nil, fail("unknown or repeated settlement character")
+ }
+ seen[index] = true
+ found := false
+ for i := range r.Characters {
+ c := &r.Characters[i]
+ if c.Index != index {
+ continue
+ }
+ if n(raw, 2) != c.ID || n(raw, 3) > c.MaxHP {
+ return nil, fail("invalid settlement health")
+ }
+ c.HP = n(raw, 3)
+ found = true
+ }
+ if !found {
+ return nil, fail("settlement character unowned")
+ }
+ }
+ if len(chars) != len(participants) {
+ return nil, fail("missing settlement characters")
+ }
+ r.Encounter = ""
+ var score, bundle []byte
+ var f uint64
+ var cleared *room
+ if mode == 27 {
+ damage := n(b, 9)
+ if damage > math.MaxInt64 {
+ return nil, fail("crystal damage overflow")
+ }
+ r.Crystal = damage
+ score, bundle, e = s.finish(ctx, v, true, false, key+":crystal")
+ } else if result != 1 {
+ score, bundle, e = s.finish(ctx, v, false, false, key+":defeat")
+ } else {
+ var eventReward []byte
+ beforeGold := r.Gold
+ for _, effect := range r.DeferredEffects {
+ x, err := s.applyEffect(v, effect)
+ if err != nil {
+ return nil, err
+ }
+ eventReward = append(eventReward, x...)
+ }
+ r.DeferredEffects = nil
+ if r.Gold != beforeGold {
+ eventReward = wire.AppendVarint(eventReward, 1, r.Gold-beforeGold)
+ }
+ if len(eventReward) > 0 {
+ out = wire.AppendBytes(out, 20, eventReward)
+ }
+ _, room := s.current(r)
+ gold := uint64(float64(room.V(3)) * s.design.Levels.Row(0, r.Level).D(5) * (1 + s.systemEffect(r, 1) + s.systemEffect(r, bonusGoldType(room.V(10)))))
+ r.Gold += gold
+ out = wire.AppendVarint(out, 21, gold)
+ switch room.V(10) {
+ case 2:
+ r.Elites++
+ case 3:
+ r.Bosses++
+ }
+ if r.Floor == uint64(len(r.Floors)) {
+ f, cleared = s.clearRoom(r)
+ if r.Level >= s.design.Default.V(14) && f >= s.design.Default.V(13) {
+ r.State = 9
+ r.Room = 0
+ r.BattleLevel = s.design.Default.V(17)
+ } else {
+ score, bundle, e = s.finish(ctx, v, true, false, fmt.Sprintf("%s:clear", key))
+ }
+ } else if r.State == 2 || r.State == 6 || r.State == 7 {
+ } else if room.V(4) > 0 {
+ r.State = 1
+ r.Remaining = room.V(4)
+ e = s.newChoice(r, 1, 0, false)
+ } else {
+ f, cleared = s.clearRoom(r)
+ }
+ }
+ if e != nil {
+ return nil, e
+ }
+ out = wire.AppendBytes(out, 17, stateWire(v.Run))
+ if v.Run != nil {
+ out = deckWire(out, 30, v.Run)
+ out = wire.AppendBytes(out, 18, choiceWire(v.Run))
+ out = wire.AppendVarint(out, 19, v.Run.Reroll)
+ for _, c := range v.Run.Characters {
+ out = wire.AppendBytes(out, 3, charWire(c, s.design.Default.V(7)))
+ }
+ }
+ if score != nil {
+ out = wire.AppendBytes(out, 22, score)
+ }
+ if bundle != nil {
+ out = wire.AppendBytes(out, 5, bundle)
+ }
+ if f > 0 && cleared != nil {
+ out = wire.AppendVarint(out, 23, f)
+ out = wire.AppendBytes(out, 24, roomWire(*cleared))
+ }
+ if e = s.save(ctx, v); e != nil {
+ return nil, e
+ }
+ return out, nil
+}
+func (s *Service) AbandonBattle(ctx command.Context) error {
+ v, _, e := s.load(ctx)
+ if e != nil {
+ return e
+ }
+ if v.Run != nil {
+ v.Run.Encounter = ""
+ }
+ return s.save(ctx, v)
+}
diff --git a/go/internal/server/domain/battle/roguelike/branches_test.go b/go/internal/server/domain/battle/roguelike/branches_test.go
new file mode 100644
index 0000000..1536451
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/branches_test.go
@@ -0,0 +1,290 @@
+//go:build integration
+
+package roguelike
+
+import (
+ "bd2server/internal/server/domain/battle"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+ "bytes"
+ "math"
+ "testing"
+)
+
+type seasonBoard struct{ total uint64 }
+
+func (b seasonBoard) Total(command.Context, uint64) (uint64, error) { return b.total, nil }
+func (b seasonBoard) Snapshot(_ command.Context, _ uint64, mine RankEntry) ([]RankEntry, RankEntry, error) {
+ mine.Rank = 2
+ return []RankEntry{{Owner: 99, Score: 1, Rank: 1}, mine}, mine, nil
+}
+
+// Event semantics are read from RogueLikeInfo.ERogueLikeEventType and
+// RogueLikeEventUI; upgrades, recipe matching, and payout are exercised through
+// protocol requests against real current rules, with state persisted between them.
+func TestEventShopRelicGrowthAndSeasonPayoutLifecycle(t *testing.T) {
+ d := currentDesign(t)
+ store := stateio.NewMemory()
+ ctx := command.Context{Identity: command.Identity{AccountID: "branch-player", SessionID: "branch-login"}, State: store}
+ economy := &testEconomy{}
+ period := Period{Season: 1, Active: true}
+ proof := battle.SettlementEvidence{}
+ access := true
+ tickets := uint64(0)
+ configure := func() *Service {
+ s, e := Open(stateio.EntrySnapshotStore{Domain: "battle", Bucket: "gameplay"}, d, Options{Owner: 4, Access: func(command.Context) error {
+ if !access {
+ return fail("locked")
+ }
+ return nil
+ }, Economy: economy, Period: func(command.Context) (Period, error) { return period, nil }, Tickets: func(_ command.Context, _ string, c uint64) error { tickets += c; return nil }, Evidence: func(command.Context) battle.SettlementEvidence { return proof }, Ranking: seasonBoard{total: math.MaxInt64}})
+ if e != nil {
+ t.Fatal(e)
+ }
+ s.sample = func(uint64) uint64 { return 0 }
+ return s
+ }
+ s := configure()
+ access = false
+ assertRejected(t, s, ctx, "Enter", req(1, 1))
+ if tickets != 0 {
+ t.Fatal("locked player consumed tickets")
+ }
+ access = true
+ rpc(t, s, ctx, "Enter", req(2, 1))
+ seq := uint64(3)
+ for range 5 {
+ v, _, e := s.load(ctx)
+ if e != nil {
+ t.Fatal(e)
+ }
+ rpc(t, s, ctx, "SelectReward", req(seq, 1, 0, v.Run.Choice[0]))
+ seq++
+ }
+ v, _, _ := s.load(ctx)
+ r := v.Run
+ // A persisted server-selected event option grants gold. Find the semantic
+ // GetGold option, rather than depending on a particular event ID or amount.
+ var eventKey [2]uint64
+ var option uint64
+ for key, event := range d.Events.Rows {
+ for i, id := range event.A(1) {
+ if d.Effects.Row(0, id).V(1) == 2 && event.A(10)[i] == 100 {
+ eventKey = key
+ option = uint64(i + 1)
+ break
+ }
+ }
+ if option > 0 {
+ break
+ }
+ }
+ if option == 0 {
+ t.Fatal("current rules contain no guaranteed gold event")
+ }
+ r.State = 5
+ r.Room = 1
+ r.EventGroup = eventKey[0]
+ r.EventID = eventKey[1]
+ beforeGold := r.Gold
+ if e := s.save(ctx, v); e != nil {
+ t.Fatal(e)
+ }
+ eventReq := req(seq, option)
+ seq++
+ eventOut := rpc(t, s, ctx, "EventSelect", eventReq)
+ if !bytes.Equal(eventOut, rpc(t, s, ctx, "EventSelect", eventReq)) {
+ t.Fatal("event retry rerolled outcome")
+ }
+ s = configure()
+ v, _, _ = s.load(ctx)
+ if v.Run.Gold <= beforeGold || v.Run.State != 0 {
+ t.Fatal("event did not award local gold and complete the room")
+ }
+ // Shop stock persists, buying consumes the offer exactly once, and owned
+ // costumes can be upgraded instead of disappearing from subsequent offers.
+ r = v.Run
+ r.Floor = 2
+ r.Room = 1
+ r.State = 4
+ r.Gold = math.MaxInt32 / 2
+ var shopRoom room
+ for key, rule := range d.Rooms.Rows {
+ if rule.V(10) == 6 {
+ shopRoom = room{Number: 1, Group: key[0], ID: key[1]}
+ break
+ }
+ }
+ r.Floors[1].Rooms = []room{shopRoom}
+ if e := s.newShop(v); e != nil {
+ t.Fatal(e)
+ }
+ if e := s.save(ctx, v); e != nil {
+ t.Fatal(e)
+ }
+ s = configure()
+ v, _, _ = s.load(ctx)
+ stock := v.Run.Shop[0]
+ gold := v.Run.Gold
+ buy := req(seq, stock.Type, stock.ID)
+ seq++
+ purchased := rpc(t, s, ctx, "ShopBuy", buy)
+ if !bytes.Equal(purchased, rpc(t, s, ctx, "ShopBuy", buy)) {
+ t.Fatal("shop retry changed receipt")
+ }
+ v, _, _ = s.load(ctx)
+ if v.Run.Gold >= gold {
+ t.Fatal("shop purchase did not consume run currency")
+ }
+ assertRejected(t, s, ctx, "ShopBuy", req(seq, stock.Type, stock.ID))
+ seq++
+ var upgrade costume
+ for _, c := range v.Run.Costumes {
+ if c.ID == stock.ID {
+ upgrade = c
+ }
+ }
+ if upgrade.Index == 0 {
+ t.Fatal("shop costume not owned")
+ }
+ rpc(t, s, ctx, "CostumeUpgrade", req(seq, upgrade.Index, 1))
+ seq++
+ v, _, _ = s.load(ctx)
+ found := false
+ for _, c := range v.Run.Costumes {
+ if c.Index == upgrade.Index && c.Level > upgrade.Level {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("shop upgrade not persisted")
+ }
+ // Use an authored recipe as the scenario setup, then exercise the public
+ // atomic consumption and reject reusing the consumed instances.
+ recipe := d.Mix.Row(0, d.Mix.Groups[0][0])
+ left, e := s.addRelic(v, recipe.V(2))
+ if e != nil {
+ t.Fatal(e)
+ }
+ right, e := s.addRelic(v, recipe.V(3))
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = s.save(ctx, v); e != nil {
+ t.Fatal(e)
+ }
+ mix := wire.AppendVarint(wire.AppendVarint(req(seq), 2, left.Index), 2, right.Index)
+ seq++
+ rpc(t, s, ctx, "RelicMix", mix)
+ s = configure()
+ v, _, _ = s.load(ctx)
+ haveResult := false
+ for _, item := range v.Run.Relics {
+ if item.Index == left.Index || item.Index == right.Index {
+ t.Fatal("recipe material survived mix")
+ }
+ if item.ID == recipe.V(4) {
+ haveResult = true
+ }
+ }
+ if !haveResult {
+ t.Fatal("recipe output absent")
+ }
+ changedMix, _, _ := wire.ReplaceVarint(mix, 1, seq)
+ seq++
+ assertRejected(t, s, ctx, "RelicMix", changedMix)
+ // Permanent growth is purchased between runs and carried into the next
+ // independent roster. The value is a relationship, not a fixed table amount.
+ rpc(t, s, ctx, "GiveUp", req(seq))
+ seq++
+ v, _, _ = s.load(ctx)
+ growth := d.Growth.Row(1, 1)
+ v.Obsidian = growth.V(8)
+ if e = s.save(ctx, v); e != nil {
+ t.Fatal(e)
+ }
+ request := wire.AppendBytes(req(seq), 2, wire.AppendVarint(wire.AppendVarint(nil, 1, 1), 2, 1))
+ seq++
+ rpc(t, s, ctx, "Growth", request)
+ s = configure()
+ rpc(t, s, ctx, "Enter", req(seq, 1))
+ seq++
+ v, _, _ = s.load(ctx)
+ id := v.Run.Choice[0]
+ rpc(t, s, ctx, "SelectReward", req(seq, 1, 0, id))
+ seq++
+ v, _, _ = s.load(ctx)
+ if v.Run.Characters[0].MaxHP <= d.Costumes[id].Health {
+ t.Fatal("purchased HP growth did not affect new run")
+ }
+ for remaining := v.Run.Remaining; remaining > 0; remaining-- {
+ rpc(t, s, ctx, "SelectReward", req(seq, 1, 0, v.Run.Choice[0]))
+ seq++
+ v, _, _ = s.load(ctx)
+ }
+ character := v.Run.Characters[0]
+ var outfit costume
+ for _, c := range v.Run.Costumes {
+ if c.Index == character.Costume {
+ outfit = c
+ }
+ }
+ deck := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, character.Index), 2, 0), 3, 1)
+ rpc(t, s, ctx, "DeckSave", wire.AppendBytes(req(seq), 2, deck))
+ seq++
+ rpc(t, s, ctx, "RoomEnter", req(seq, 1))
+ seq++
+ v, _, _ = s.load(ctx)
+ battleDeck, mode := s.battleRule(v.Run)
+ if _, e = s.EnterBattle(ctx, req(seq, 0, 0, battleDeck, mode), "grown-battle"); e != nil {
+ t.Fatal(e)
+ }
+ seq++
+ proof = battle.SettlementEvidence{Receipt: "grown-battle", Mode: mode, Deck: battleDeck}
+ blue := wire.AppendVarint(nil, 1, 1)
+ for _, f := range []struct {
+ n int
+ v uint64
+ }{{2, character.Index}, {3, character.ID}, {4, character.HP}, {5, d.Default.V(7)}, {6, outfit.Index}, {7, outfit.ID}, {8, outfit.Level}} {
+ blue = wire.AppendVarint(blue, f.n, f.v)
+ }
+ start := wire.AppendBytes(wire.AppendBytes(req(seq, battleDeck), 3, deck), 5, blue)
+ seq++
+ for i, enemy := range d.Enemies[battleDeck] {
+ red := wire.AppendVarint(nil, 1, uint64(i+2))
+ red = wire.AppendVarint(red, 3, enemy.ID)
+ red = wire.AppendVarint(red, 4, 1)
+ red = wire.AppendVarint(red, 5, enemy.Level)
+ red = wire.AppendVarint(red, 9, enemy.Position)
+ start = wire.AppendBytes(start, 4, red)
+ }
+ if e = s.ValidateBattleStart(ctx, start); e != nil {
+ t.Fatalf("legitimate HP growth battle refused: %v", e)
+ }
+ proof.Round = 1
+ proof.InitialBlue = [][]byte{blue}
+ if _, e = s.CompleteBattle(ctx, wire.AppendBytes(req(seq, 1), 3, charWire(character, d.Default.V(7))), "grown-battle"); e != nil {
+ t.Fatal(e)
+ }
+ seq++
+ rpc(t, s, ctx, "GiveUp", req(seq))
+ seq++
+ period.Season = 2
+ s = configure()
+ beforeRewards := economy.rewards
+ claim := req(seq)
+ seq++
+ seasonReply := rpc(t, s, ctx, "SeasonReward", claim)
+ if economy.rewards <= beforeRewards || n(seasonReply, 1) != 2 {
+ t.Fatal("completed season did not use real global threshold rewards and personal rank")
+ }
+ if !bytes.Equal(seasonReply, rpc(t, s, ctx, "SeasonReward", claim)) {
+ t.Fatal("season reward retry changed receipt")
+ }
+ paid := economy.rewards
+ assertRejected(t, s, ctx, "SeasonReward", req(seq))
+ if economy.rewards != paid {
+ t.Fatal("completed season paid twice")
+ }
+}
diff --git a/go/internal/server/domain/battle/roguelike/costume_offers.go b/go/internal/server/domain/battle/roguelike/costume_offers.go
new file mode 100644
index 0000000..78249c0
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/costume_offers.go
@@ -0,0 +1,52 @@
+package roguelike
+
+func (s *Service) costumePool(r *run, initial bool) []uint64 {
+ var pool []uint64
+ for _, id := range s.design.CostumeIDs {
+ design := s.design.Costumes[id]
+ if s.options.CostumeVisible != nil && !s.options.CostumeVisible(id) {
+ continue
+ }
+ if design.RequiresOwnership && (s.options.CostumeOwned == nil || !s.options.CostumeOwned(id)) {
+ continue
+ }
+ eligible := true
+ for _, c := range r.Costumes {
+ if c.ID == id && (initial || c.Level >= design.MaxLevel) {
+ eligible = false
+ break
+ }
+ }
+ if eligible {
+ pool = append(pool, id)
+ }
+ }
+ return pool
+}
+
+func (s *Service) pickCostume(r *run, pool []uint64, option uint64, initial bool) (uint64, []uint64, bool) {
+ if len(pool) == 0 {
+ return 0, pool, false
+ }
+ var preferred []int
+ for i, id := range pool {
+ owned := false
+ for _, c := range r.Costumes {
+ if c.ID == id {
+ owned = true
+ break
+ }
+ }
+ if initial || (option == 1 && owned) || (option == 2 && !owned) {
+ preferred = append(preferred, i)
+ }
+ }
+ var at int
+ if len(preferred) > 0 {
+ at = preferred[s.sample(uint64(len(preferred)))]
+ } else {
+ at = int(s.sample(uint64(len(pool))))
+ }
+ id := pool[at]
+ return id, append(pool[:at], pool[at+1:]...), true
+}
diff --git a/go/internal/server/domain/battle/roguelike/costume_offers_test.go b/go/internal/server/domain/battle/roguelike/costume_offers_test.go
new file mode 100644
index 0000000..cf7efc8
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/costume_offers_test.go
@@ -0,0 +1,186 @@
+//go:build integration
+
+package roguelike
+
+import (
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/storage/stateio"
+ "math"
+ "slices"
+ "testing"
+)
+
+// LocalTextTable 1600225 defines the first five distinct choices, later two
+// acquired/two unacquired offers, and account ownership for new/collaboration costumes.
+func TestCostumeOffersRespectAccountOwnershipAndRunAcquisitions(t *testing.T) {
+ d := currentDesign(t)
+ var ordinary, restricted []uint64
+ for _, id := range d.CostumeIDs {
+ if d.Costumes[id].MaxLevel == 0 {
+ continue
+ }
+ if d.Costumes[id].RequiresOwnership {
+ restricted = append(restricted, id)
+ } else {
+ ordinary = append(ordinary, id)
+ }
+ }
+ if len(ordinary) < 12 || len(restricted) < 2 {
+ t.Fatal("real design lacks distinct eligible ownership pools")
+ }
+ account := map[uint64]bool{restricted[0]: true}
+ s := &Service{design: d, options: Options{CostumeOwned: func(id uint64) bool { return account[id] }}, sample: func(uint64) uint64 { return 0 }}
+ r := &run{Level: 1}
+ if e := s.newChoice(r, 1, 0, true); e != nil {
+ t.Fatal(e)
+ }
+ if !slices.Contains(r.Choice, restricted[0]) || slices.Contains(r.Choice, restricted[1]) || !slices.Contains(r.Choice, ordinary[0]) {
+ t.Fatal("wildcard did not distinguish account-owned restricted costumes from ordinary unowned costumes")
+ }
+ delete(account, restricted[0])
+ if e := s.newChoice(r, 1, 0, true); e != nil {
+ t.Fatal(e)
+ }
+ if slices.Contains(r.Choice, restricted[0]) {
+ t.Fatal("account ownership changes were ignored")
+ }
+ account[restricted[0]] = true
+ acquired := []uint64{ordinary[0], ordinary[1], ordinary[2], restricted[0]}
+ for i, id := range acquired {
+ r.Costumes = append(r.Costumes, costume{Index: uint64(i + 1), ID: id})
+ }
+ maxed := ordinary[3]
+ r.Costumes = append(r.Costumes, costume{Index: 5, ID: maxed, Level: d.Costumes[maxed].MaxLevel})
+ if e := s.newChoice(r, 1, 0, false); e != nil {
+ t.Fatal(e)
+ }
+ for _, id := range r.Choice {
+ if slices.Contains(acquired, id) || id == maxed {
+ t.Fatal("initial draft offered an already acquired costume")
+ }
+ }
+ r.Room, r.Floor = 1, 1
+ check := func(ids []uint64, expectedOwned int) {
+ t.Helper()
+ seen := map[uint64]bool{}
+ owned := 0
+ for _, id := range ids {
+ if seen[id] || id == maxed || (d.Costumes[id].RequiresOwnership && !account[id]) {
+ t.Fatalf("invalid, duplicate, maxed, or account-locked offer %d", id)
+ }
+ seen[id] = true
+ if slices.Contains(acquired, id) {
+ owned++
+ }
+ }
+ if owned != expectedOwned {
+ t.Fatalf("acquired offers = %d, want %d (total %d)", owned, expectedOwned, len(ids))
+ }
+ }
+ if e := s.newChoice(r, 1, 0, false); e != nil {
+ t.Fatal(e)
+ }
+ if len(r.Choice) != 4 {
+ t.Fatal("normal reward lacks four choices despite sufficient eligible pools")
+ }
+ check(r.Choice, 2)
+ for key, rule := range d.Rooms.Rows {
+ if rule.V(10) == 6 && d.Shops.Row(0, rule.V(9)).Values != nil {
+ r.Floors = []floor{{Number: 1, Rooms: []room{{Number: 1, Group: key[0], ID: key[1]}}}}
+ break
+ }
+ }
+ if len(r.Floors) == 0 {
+ t.Fatal("real design has no shop room")
+ }
+ v := &state{Run: r}
+ if e := s.newShop(v); e != nil {
+ t.Fatal(e)
+ }
+ var shopIDs []uint64
+ for _, o := range r.Shop {
+ if o.Type == 1 {
+ shopIDs = append(shopIDs, o.ID)
+ }
+ }
+ if len(shopIDs) != 8 {
+ t.Fatal("real shop lacks eight costume offers despite sufficient eligible pools")
+ }
+ check(shopIDs, 4)
+ _, upgraded, e := s.addCostume(command.Context{}, v, acquired[0])
+ if e != nil || upgraded.Level != 1 || len(r.Costumes) != 5 {
+ t.Fatal("a later acquired offer cannot upgrade its existing run costume")
+ }
+ r.Costumes = nil
+ for i, id := range d.CostumeIDs {
+ level := d.Costumes[id].MaxLevel
+ if slices.Contains(acquired[:3], id) {
+ level = 0
+ }
+ r.Costumes = append(r.Costumes, costume{Index: uint64(i + 1), ID: id, Level: level})
+ }
+ if e = s.newChoice(r, 1, 0, false); e != nil {
+ t.Fatalf("exhausted unacquired pool blocked the run: %v", e)
+ }
+ if len(r.Choice) != 3 {
+ t.Fatal("pool exhaustion should return each remaining upgrade once")
+ }
+ check(r.Choice, 3)
+}
+
+// ScheduleSeason transitions to off-season after End+Calculate while retaining
+// the same season ID; Info triggers the native reward request through field 21.
+func TestSeasonRewardUnlocksAfterCalculationWithoutSeasonIDChange(t *testing.T) {
+ d := currentDesign(t)
+ store := stateio.NewMemory()
+ ctx := command.Context{Identity: command.Identity{AccountID: "settled-player", SessionID: "settled-login"}, State: store}
+ period := Period{Season: 97}
+ settled := false
+ economy := &testEconomy{}
+ open := func() *Service {
+ t.Helper()
+ s, e := Open(stateio.EntrySnapshotStore{Domain: "battle", Bucket: "gameplay"}, d, Options{
+ Access: func(command.Context) error { return nil }, Economy: economy,
+ Period: func(command.Context) (Period, error) { return period, nil },
+ Tickets: func(command.Context, string, uint64) error { return nil },
+ SeasonSettled: func(id uint64) bool { return id == period.Season && settled },
+ Ranking: seasonBoard{total: math.MaxInt64},
+ })
+ if e != nil {
+ t.Fatal(e)
+ }
+ return s
+ }
+ s := open()
+ v, _, e := s.load(ctx)
+ if e != nil {
+ t.Fatal(e)
+ }
+ v.Seasons[period.Season] = seasonRecord{Score: 1}
+ if e = s.save(ctx, v); e != nil {
+ t.Fatal(e)
+ }
+ if info := rpc(t, s, ctx, "Info", req(1)); n(info, 19) != period.Season || n(info, 21) != 0 {
+ t.Fatal("unsettled season advertised a reward")
+ }
+ assertRejected(t, s, ctx, "SeasonReward", req(2))
+ if economy.calls != 0 {
+ t.Fatal("calculation paid before settlement")
+ }
+ settled = true
+ s = open()
+ if info := rpc(t, s, ctx, "Info", req(3)); n(info, 19) != period.Season || n(info, 21) != 1 {
+ t.Fatal("settled current season did not advertise its native reward request")
+ }
+ claim := req(4)
+ rpc(t, s, ctx, "SeasonReward", claim)
+ if economy.calls != 1 || economy.rewards == 0 {
+ t.Fatal("settled same-ID season did not pay actual threshold rewards")
+ }
+ s = open()
+ rpc(t, s, ctx, "SeasonReward", claim)
+ assertRejected(t, s, ctx, "SeasonReward", req(5))
+ if info := rpc(t, s, ctx, "Info", req(6)); n(info, 21) != 0 || economy.calls != 1 {
+ t.Fatal("settled claim did not persist or retry paid again")
+ }
+}
diff --git a/go/internal/server/domain/battle/roguelike/events.go b/go/internal/server/domain/battle/roguelike/events.go
new file mode 100644
index 0000000..6edd10c
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/events.go
@@ -0,0 +1,202 @@
+package roguelike
+
+import (
+ "bd2server/internal/server/protocol/wire"
+ "slices"
+)
+
+func (s *Service) eventSelect(v *state, choice uint64) ([]byte, error) {
+ r := v.Run
+ if r.State != 5 || r.EventGroup == 0 {
+ return nil, fail("no event selection")
+ }
+ event := s.design.Events.Row(r.EventGroup, r.EventID)
+ if choice == 0 {
+ if event.V(11) == 0 {
+ return nil, fail("event exit unavailable")
+ }
+ f, rm := s.clearRoom(r)
+ b := clearedResponse(r, f, rm, 1, 3, 5)
+ return wire.AppendVarint(b, 2, 1), nil
+ }
+ if choice > uint64(len(event.A(7))) {
+ return nil, fail("unknown event option")
+ }
+ i := choice - 1
+ success := s.sample(10000) < uint64(min(1.0, float64(event.A(10)[i])/100+s.systemEffect(r, 6))*10000)
+ effect := event.A(1)[i]
+ if !success {
+ effect = event.A(2)[i]
+ }
+ effects := []uint64{effect}
+ if success && i < uint64(len(event.A(3))) {
+ effects = append(effects, event.A(3)[i])
+ }
+ var reward []byte
+ before := r.Gold
+ for _, id := range effects {
+ if id == 0 {
+ continue
+ }
+ if r.State == 3 {
+ r.DeferredEffects = append(r.DeferredEffects, id)
+ continue
+ }
+ x, e := s.applyEffect(v, id)
+ if e != nil {
+ return nil, e
+ }
+ reward = append(reward, x...)
+ }
+ reward = wire.AppendVarint(reward, 1, uint64(int64(r.Gold)-int64(before)))
+ r.Events++
+ var f uint64
+ var room *room
+ if r.State == 5 {
+ f, room = s.clearRoom(r)
+ }
+ if r.ChoiceType > 0 {
+ reward = wire.AppendBytes(reward, 5, choiceWire(r))
+ }
+ if r.State == 3 {
+ reward = wire.AppendVarint(reward, 6, r.BattleLevel)
+ }
+ b := clearedResponse(r, f, room, 1, 3, 5)
+ result := uint64(2)
+ if success {
+ result = 1
+ }
+ b = wire.AppendVarint(b, 2, result)
+ b = wire.AppendBytes(b, 4, reward)
+ return wire.AppendVarint(b, 6, r.Reroll), nil
+}
+func (s *Service) applyEffect(v *state, id uint64) ([]byte, error) {
+ r := v.Run
+ effect := s.design.Effects.Row(0, id)
+ if effect.Values == nil {
+ return nil, fail("missing event effect")
+ }
+ a, z := effect.V(2), effect.V(3)
+ var b []byte
+ switch effect.V(1) {
+ case 1:
+ r.State = 3
+ r.BattleLevel = a
+ case 2:
+ if z < a {
+ return nil, fail("invalid gold range")
+ }
+ r.Gold += a + s.sample(z-a+1)
+ case 3:
+ if r.Gold < a {
+ return nil, fail("insufficient event gold")
+ }
+ r.Gold -= a
+ case 4, 5:
+ sign := int64(1)
+ if effect.V(1) == 5 {
+ sign = -1
+ }
+ for i := range r.Characters {
+ c := &r.Characters[i]
+ delta := int64(c.MaxHP*a/100) * sign
+ hp := int64(c.HP) + delta
+ hp = max(hp, 0)
+ hp = min(hp, int64(c.MaxHP))
+ c.HP = uint64(hp)
+ b = wire.AppendBytes(b, 2, charWire(*c, s.design.Default.V(7)))
+ }
+ b = wire.AppendVarint(b, 7, uint64(int64(a)*sign))
+ case 6:
+ item, e := s.addRelic(v, a)
+ if e != nil {
+ return nil, e
+ }
+ b = wire.AppendBytes(b, 3, relicWire(item))
+ case 7:
+ itemID, e := s.rollRelic(r, s.design.RelicChoices.Row(0, a), nil)
+ if e != nil {
+ return nil, e
+ }
+ item, e := s.addRelic(v, itemID)
+ if e != nil {
+ return nil, e
+ }
+ b = wire.AppendBytes(b, 3, relicWire(item))
+ case 8:
+ r.State = 2
+ r.Remaining = 1
+ if e := s.newChoice(r, 2, a, false); e != nil {
+ return nil, e
+ }
+ case 9:
+ if len(r.Relics) == 0 {
+ return nil, fail("no relic to exchange")
+ }
+ for _, item := range r.Relics {
+ if item.ID == a {
+ return nil, fail("exchange result owned")
+ }
+ }
+ r.State = 6
+ r.PendingRelic = a
+ case 10:
+ if len(r.Relics) == 0 {
+ return nil, fail("no relic to exchange")
+ }
+ index := s.sample(uint64(len(r.Relics)))
+ old := r.Relics[index]
+ newID, e := s.rollRelic(r, s.design.RelicChoices.Row(0, a), nil)
+ if e != nil {
+ return nil, e
+ }
+ r.Relics = append(r.Relics[:index], r.Relics[index+1:]...)
+ add, e := s.addRelic(v, newID)
+ if e != nil {
+ return nil, e
+ }
+ b = wire.AppendBytes(b, 4, relicWire(old))
+ b = wire.AppendBytes(b, 3, relicWire(add))
+ case 11:
+ if len(r.Relics) == 0 {
+ return nil, fail("no relic to remove")
+ }
+ r.State = 7
+ case 12:
+ if len(r.Relics) == 0 {
+ return nil, fail("no relic to remove")
+ }
+ i := s.sample(uint64(len(r.Relics)))
+ b = wire.AppendBytes(b, 4, relicWire(r.Relics[i]))
+ r.Relics = append(r.Relics[:i], r.Relics[i+1:]...)
+ default:
+ return nil, fail("unsupported event effect")
+ }
+ return b, nil
+}
+func (s *Service) eventChoice(v *state, typ, id uint64) ([]byte, error) {
+ r := v.Run
+ if typ != 2 || r.State != 6 && r.State != 7 {
+ return nil, fail("no pending relic selection")
+ }
+ i := slices.IndexFunc(r.Relics, func(a relic) bool { return a.ID == id })
+ if i < 0 {
+ return nil, fail("selected relic unowned")
+ }
+ old := r.Relics[i]
+ r.Relics = slices.Delete(r.Relics, i, i+1)
+ reward := wire.AppendBytes(nil, 4, relicWire(old))
+ if r.State == 6 {
+ add, e := s.addRelic(v, r.PendingRelic)
+ if e != nil {
+ return nil, e
+ }
+ reward = wire.AppendBytes(reward, 3, relicWire(add))
+ }
+ r.PendingRelic = 0
+ f, rm := s.clearRoom(r)
+ out := clearedResponse(r, f, rm, 1, 3, 5)
+ out = wire.AppendVarint(out, 2, 1)
+ out = wire.AppendBytes(out, 4, reward)
+ return wire.AppendVarint(out, 6, r.Reroll), nil
+}
diff --git a/go/internal/server/domain/battle/roguelike/lifecycle_test.go b/go/internal/server/domain/battle/roguelike/lifecycle_test.go
new file mode 100644
index 0000000..7c30eb8
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/lifecycle_test.go
@@ -0,0 +1,266 @@
+//go:build integration
+
+package roguelike
+
+import (
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/battle"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+ "bytes"
+ "encoding/binary"
+ "fmt"
+ "testing"
+)
+
+type testEconomy struct {
+ rewards int
+ calls int
+}
+
+func (e *testEconomy) Apply(_ command.Context, _ string, _ []gamedata.Reward, rewards []gamedata.Reward) ([]byte, error) {
+ e.calls++
+ for _, r := range rewards {
+ e.rewards += int(r.Count)
+ }
+ return []byte{8, 1}, nil
+}
+func currentDesign(t *testing.T) *gamedata.RogueLikeDesign {
+ t.Helper()
+ v, e := versionconfig.Find()
+ if e != nil {
+ t.Fatal(e)
+ }
+ versionconfig.Use(v)
+ d, e := gamedata.LoadRogueLikeDesign(v.Resolve("data/resources/GameData"), v.GameDataVersion)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return d
+}
+func req(seq uint64, fields ...uint64) []byte {
+ b := wire.AppendVarint(nil, 1, seq)
+ for i, v := range fields {
+ b = wire.AppendVarint(b, i+2, v)
+ }
+ return b
+}
+func rpc(t *testing.T, s *Service, ctx command.Context, op string, b []byte) []byte {
+ t.Helper()
+ _, out, ok, e := s.Handle(ctx, "/EvilCastleRogueLike"+op, b)
+ if e != nil || !ok {
+ t.Fatalf("%s handled=%t err=%v", op, ok, e)
+ }
+ return out
+}
+func firstMessage(t *testing.T, b []byte, f int) []byte {
+ t.Helper()
+ a, e := messages(b, f)
+ if e != nil || len(a) == 0 {
+ t.Fatalf("missing message field %d: %v", f, e)
+ }
+ return a[0]
+}
+func assertRejected(t *testing.T, s *Service, ctx command.Context, op string, b []byte) {
+ t.Helper()
+ _, _, ok, e := s.Handle(ctx, "/EvilCastleRogueLike"+op, b)
+ if !ok || e == nil {
+ t.Fatalf("%s accepted invalid command", op)
+ }
+}
+
+// The current client contracts are RogueLikePacket (initial draft and reward
+// deltas), RogueLikeMainUI.GetConnectRoomList, and BattlePacket (normal battle
+// transport). This exercise uses real versioned rules, not response fixtures.
+func TestRunReopenBattleSettlementAndFirstClearCannotPayTwice(t *testing.T) {
+ d := currentDesign(t)
+ store := stateio.NewMemory()
+ ctx := command.Context{Identity: command.Identity{AccountID: "rogue-a", SessionID: "login-a"}, State: store}
+ period := Period{Season: 1, Regular: 1, Active: true}
+ economy := &testEconomy{}
+ tickets := uint64(0)
+ proof := battle.SettlementEvidence{}
+ open := func() *Service {
+ s, e := Open(stateio.EntrySnapshotStore{Domain: "battle", Bucket: "gameplay"}, d, Options{Access: func(command.Context) error { return nil }, Economy: economy, Owner: 1, Period: func(command.Context) (Period, error) { return period, nil }, Tickets: func(_ command.Context, _ string, count uint64) error { tickets += count; return nil }, Evidence: func(command.Context) battle.SettlementEvidence { return proof }})
+ if e != nil {
+ t.Fatal(e)
+ }
+ s.sample = func(uint64) uint64 { return 0 }
+ return s
+ }
+ s := open()
+ seq := uint64(1)
+ assertRejected(t, s, ctx, "QuickBattle", req(seq, 1, 1))
+ seq++
+ enterReq := req(seq, 1)
+ enter := rpc(t, s, ctx, "Enter", enterReq)
+ if !bytes.Equal(enter, rpc(t, s, ctx, "Enter", enterReq)) || tickets == 0 {
+ t.Fatal("entry retry changed map or lost ticket charge")
+ }
+ charged := tickets
+ seq++
+ assertRejected(t, s, ctx, "Enter", req(seq, 1))
+ seq++
+ draftUnique := map[uint64]bool{}
+ for range 5 {
+ info := rpc(t, s, ctx, "Info", req(seq))
+ seq++
+ choice := firstMessage(t, info, 8)
+ ids := []uint64{}
+ _ = wire.Walk(choice, func(f wire.Field) error {
+ if f.Number == 2 {
+ value, k := binary.Uvarint(f.Value)
+ if k <= 0 {
+ return wire.ErrMalformed
+ }
+ ids = append(ids, value)
+ }
+ return nil
+ })
+ if len(ids) == 0 {
+ t.Fatal("initial draft ended before the client's five starting costumes")
+ }
+ id := ids[0]
+ for _, candidate := range ids {
+ unique := d.Costumes[candidate].Unique
+ if !draftUnique[unique] {
+ id = candidate
+ draftUnique[unique] = true
+ break
+ }
+ }
+ rpc(t, s, ctx, "SelectReward", req(seq, 1, 0, id))
+ seq++
+ s = open()
+ }
+ info := rpc(t, s, ctx, "Info", req(seq))
+ seq++
+ costumes, _ := messages(info, 6)
+ chars, _ := messages(info, 5)
+ if len(costumes) != 5 || len(chars) == 0 {
+ t.Fatal("reopening lost the starting roster")
+ }
+ if n(firstMessage(t, info, 1), 3) != 0 {
+ t.Fatal("draft does not lead to the map")
+ }
+ formation := req(seq)
+ seq++
+ for i, c := range chars {
+ a := wire.AppendVarint(nil, 1, n(c, 1))
+ a = wire.AppendVarint(a, 2, uint64(i))
+ a = wire.AppendVarint(a, 3, uint64(i+1))
+ formation = wire.AppendBytes(formation, 2, a)
+ }
+ rpc(t, s, ctx, "DeckSave", formation)
+ for battleNo := range 40 {
+ v, _, e := s.load(ctx)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if v.Run == nil {
+ break
+ }
+ r := v.Run
+ if r.State == 1 || r.State == 2 {
+ rpc(t, s, ctx, "SelectReward", req(seq, r.ChoiceType, 0, r.Choice[0]))
+ seq++
+ continue
+ }
+ if r.State != 0 {
+ t.Fatalf("unexpected map state %d", r.State)
+ }
+ rpc(t, s, ctx, "RoomEnter", req(seq, 1))
+ seq++
+ v, _, _ = s.load(ctx)
+ r = v.Run
+ if r.State == 4 {
+ rpc(t, s, ctx, "ShopExit", req(seq))
+ seq++
+ continue
+ }
+ if r.State == 1 || r.State == 2 {
+ continue
+ }
+ if r.State == 5 {
+ rpc(t, s, ctx, "EventSelect", req(seq, 1))
+ seq++
+ continue
+ }
+ deck, mode := s.battleRule(r)
+ identity := fmt.Sprintf("fight-%d", battleNo)
+ if _, e = s.EnterBattle(ctx, req(seq, 0, 0, deck, mode), identity); e != nil {
+ t.Fatalf("enter battle floor=%d state=%d room=%d: %v", r.Floor, r.State, r.Room, e)
+ }
+ seq++
+ proof = battle.SettlementEvidence{Receipt: identity, Mode: mode, Deck: deck, Round: 0}
+ end := req(seq, 1)
+ seq++
+ if _, e = s.CompleteBattle(ctx, end, identity); e == nil {
+ t.Fatal("settled a room without any started battle")
+ }
+ var blue [][]byte
+ for i, c := range r.Characters {
+ var costume costume
+ for _, a := range r.Costumes {
+ if a.Index == c.Costume {
+ costume = a
+ }
+ }
+ a := wire.AppendVarint(nil, 1, uint64(i+1))
+ a = wire.AppendVarint(a, 2, c.Index)
+ a = wire.AppendVarint(a, 3, c.ID)
+ a = wire.AppendVarint(a, 4, c.HP)
+ a = wire.AppendVarint(a, 5, d.Default.V(7))
+ a = wire.AppendVarint(a, 6, costume.Index)
+ a = wire.AppendVarint(a, 7, costume.ID)
+ a = wire.AppendVarint(a, 8, costume.Level)
+ a = wire.AppendVarint(a, 9, uint64(i))
+ blue = append(blue, a)
+ end = wire.AppendBytes(end, 3, charWire(c, d.Default.V(7)))
+ }
+ proof.Round = 1
+ proof.InitialBlue = blue
+ out, e := s.CompleteBattle(ctx, end, identity)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if _, e = s.CompleteBattle(ctx, end, identity); e == nil {
+ t.Fatal("domain paid a settled room twice")
+ }
+ if len(out) == 0 {
+ t.Fatal("battle omitted client state")
+ }
+ s = open()
+ }
+ v, _, e := s.load(ctx)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if v.Run != nil || v.MaxTry == 0 || v.MaxReward == 0 || economy.rewards == 0 {
+ t.Fatal("full run did not unlock sweep and credit first-clear rewards")
+ }
+ paid := economy.rewards
+ obs := v.Obsidian
+ quick := req(seq, 1, 2)
+ seq++
+ reply := rpc(t, s, ctx, "QuickBattle", quick)
+ if !bytes.Equal(reply, rpc(t, s, ctx, "QuickBattle", quick)) {
+ t.Fatal("sweep retry changed receipt")
+ }
+ if tickets <= charged || economy.rewards != paid {
+ t.Fatal("sweep did not consume tickets or repeated first-clear inventory rewards")
+ }
+ s = open()
+ v, _, _ = s.load(ctx)
+ if v.Obsidian <= obs {
+ t.Fatal("sweep growth currency was lost after reopen")
+ }
+ assertRejected(t, s, ctx, "QuickBattle", req(seq, 2, 1))
+ seq++
+ other := ctx
+ other.State = stateio.NewMemory()
+ other.AccountID = "rogue-b"
+ assertRejected(t, s, other, "QuickBattle", req(seq, 1, 1))
+}
diff --git a/go/internal/server/domain/battle/roguelike/progression.go b/go/internal/server/domain/battle/roguelike/progression.go
new file mode 100644
index 0000000..67cac8f
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/progression.go
@@ -0,0 +1,281 @@
+package roguelike
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "math"
+ "slices"
+)
+
+func rewards(rule gamedata.RogueRule, tf, idf, cf int) []gamedata.Reward {
+ var out []gamedata.Reward
+ for i, t := range rule.A(tf) {
+ if i < len(rule.A(idf)) && i < len(rule.A(cf)) && rule.A(cf)[i] > 0 {
+ out = append(out, gamedata.Reward{Type: t, ID: rule.A(idf)[i], Count: rule.A(cf)[i]})
+ }
+ }
+ return out
+}
+func (s *Service) growth(v *state, b []byte) ([]byte, error) {
+ a, e := messages(b, 2)
+ if e != nil || len(a) != 1 {
+ return nil, fail("invalid growth")
+ }
+ typ, level := n(a[0], 1), n(a[0], 2)
+ rule := s.design.Growth.Row(typ, level)
+ if rule.Values == nil || level != v.Growth[typ]+1 || v.Run != nil || v.Obsidian < rule.V(8) {
+ return nil, fail("growth unavailable or insufficient obsidian")
+ }
+ v.Obsidian -= rule.V(8)
+ v.Growth[typ] = level
+ return wire.AppendVarint(wire.AppendVarint(nil, 1, level), 2, uint64(-int64(rule.V(8)))), nil
+}
+func (s *Service) score(v *state, penalty bool) ([]byte, uint64) {
+ r := v.Run
+ if r == nil {
+ return nil, 0
+ }
+ var b []byte
+ total := uint64(0)
+ best := map[uint64]uint64{}
+ counts := map[uint64]uint64{}
+ for _, id := range s.design.Scores.Groups[0] {
+ x := s.design.Scores.Row(0, id)
+ count := uint64(0)
+ switch x.V(5) {
+ case 1:
+ count = r.Cleared
+ case 2:
+ if r.Gold >= x.V(2) {
+ count = 1
+ }
+ case 3:
+ if uint64(len(r.Relics)) >= x.V(2) {
+ count = 1
+ }
+ case 4:
+ if uint64(len(r.Characters)) <= x.V(2) {
+ count = 1
+ }
+ case 5:
+ if uint64(len(r.Characters)) >= x.V(2) {
+ count = 1
+ }
+ case 6:
+ if r.Events >= x.V(2) {
+ count = 1
+ }
+ case 7:
+ count = r.Elites
+ case 8:
+ count = r.Bosses
+ case 9:
+ count = r.Crystal / max(s.design.Default.V(18), 1)
+ }
+ if count == 0 {
+ continue
+ }
+ score := count * x.V(6)
+ typ := x.V(5)
+ if typ == 2 || typ == 3 || typ == 6 {
+ if score <= best[typ] {
+ continue
+ }
+ best[typ] = score
+ counts[typ] = id
+ continue
+ }
+ a := wire.AppendVarint(nil, 1, id)
+ a = wire.AppendVarint(a, 2, score)
+ a = wire.AppendVarint(a, 3, count)
+ b = wire.AppendBytes(b, 1, a)
+ total += score
+ }
+ for _, typ := range []uint64{2, 3, 6} {
+ if score := best[typ]; score > 0 {
+ a := wire.AppendVarint(nil, 1, counts[typ])
+ a = wire.AppendVarint(a, 2, score)
+ a = wire.AppendVarint(a, 3, 1)
+ b = wire.AppendBytes(b, 1, a)
+ total += score
+ }
+ }
+ bonus := s.design.Levels.Row(0, r.Level).D(11)
+ total = uint64(float64(total) * bonus)
+ total = min(total, math.MaxInt32)
+ obs := uint64(float64(total) * s.design.Default.D(29))
+ if penalty && !slices.Contains(s.design.Default.A(2), r.Floor-1) {
+ obs = uint64(float64(obs) * (1 - s.design.Default.D(25)))
+ }
+ b = wire.AppendVarint(b, 2, total)
+ b = wire.AppendVarint(b, 3, obs)
+ return b, obs
+}
+func (s *Service) publish(ctx command.Context, v *state, score, damage uint64) error {
+ r := v.Seasons[v.Season]
+ if r.Score > math.MaxInt64-score {
+ return fail("season score overflow")
+ }
+ r.Score += score
+ r.Damage = max(r.Damage, damage)
+ v.Seasons[v.Season] = r
+ if s.options.Publish != nil {
+ return s.options.Publish(ctx, v.Season, r.Score, r.Damage, v.NextRun)
+ }
+ return nil
+}
+func (s *Service) finish(ctx command.Context, v *state, win, penalty bool, key string) ([]byte, []byte, error) {
+ r := v.Run
+ if r == nil {
+ return nil, nil, fail("no run to finish")
+ }
+ score, obs := s.score(v, penalty)
+ var bundle []byte
+ if win {
+ v.MaxTry = max(v.MaxTry, r.Level)
+ if r.Level > v.MaxReward {
+ var grant []gamedata.Reward
+ for level := v.MaxReward + 1; level <= r.Level; level++ {
+ grant = append(grant, rewards(s.design.Levels.Row(0, level), 10, 9, 8)...)
+ }
+ var e error
+ bundle, e = s.options.Economy.Apply(ctx, key+":clear", nil, grant)
+ if e != nil {
+ return nil, nil, e
+ }
+ v.MaxReward = r.Level
+ }
+ }
+ if obs > math.MaxInt32-v.Obsidian {
+ return nil, nil, fail("obsidian overflow")
+ }
+ v.Obsidian += obs
+ v.HighestCrystal = max(v.HighestCrystal, r.Crystal)
+ if e := s.publish(ctx, v, n(score, 2), r.Crystal); e != nil {
+ return nil, nil, e
+ }
+ total, e := s.total(ctx, v)
+ if e != nil {
+ return nil, nil, e
+ }
+ score = wire.AppendVarint(score, 4, total)
+ score = wire.AppendVarint(score, 5, v.MaxTry)
+ score = wire.AppendVarint(score, 6, v.MaxReward)
+ score = wire.AppendVarint(score, 7, r.Crystal)
+ v.LastScore = score
+ v.Run = nil
+ return score, bundle, nil
+}
+func (s *Service) quick(ctx command.Context, v *state, p Period, b []byte, key string) ([]byte, error) {
+ level, count := n(b, 2), n(b, 3)
+ rule := s.design.Levels.Row(0, level)
+ if !p.Active || v.Run != nil || rule.Values == nil || level > v.MaxTry || count == 0 || count > 100 {
+ return nil, fail("quick battle requires previous clear")
+ }
+ if e := s.options.Tickets(ctx, key, count*s.design.Default.V(30)); e != nil {
+ return nil, e
+ }
+ score := rule.V(7) * count
+ obs := uint64(float64(score) * s.design.Default.D(29))
+ if obs > math.MaxInt32-v.Obsidian {
+ return nil, fail("obsidian overflow")
+ }
+ v.Obsidian += obs
+ v.NextRun++
+ if e := s.publish(ctx, v, score, 0); e != nil {
+ return nil, e
+ }
+ a := wire.AppendVarint(nil, 1, 9999)
+ a = wire.AppendVarint(a, 2, score)
+ a = wire.AppendVarint(a, 3, count)
+ out := wire.AppendBytes(nil, 1, a)
+ out = wire.AppendVarint(out, 2, score)
+ out = wire.AppendVarint(out, 3, obs)
+ total, e := s.total(ctx, v)
+ if e != nil {
+ return nil, e
+ }
+ out = wire.AppendVarint(out, 4, total)
+ out = wire.AppendVarint(out, 5, v.MaxTry)
+ out = wire.AppendVarint(out, 6, v.MaxReward)
+ return wire.AppendBytes(nil, 1, out), nil
+}
+func rankWire(a RankEntry) []byte {
+ b := append([]byte(nil), a.Profile...)
+ b = wire.AppendVarint(b, 1, a.Owner)
+ b = wire.AppendVarint(b, 7, a.Rank)
+ b = wire.AppendVarint(b, 8, min(a.Score, math.MaxInt32))
+ return wire.AppendVarint(b, 10, a.Damage)
+}
+func (s *Service) rankings(ctx command.Context, v *state, season uint64) ([]RankEntry, RankEntry, error) {
+ local := v.Seasons[season]
+ entry := RankEntry{Owner: s.options.Owner, Score: local.Score, Damage: local.Damage}
+ if s.options.Ranking != nil {
+ return s.options.Ranking.Snapshot(ctx, season, entry)
+ }
+ if entry.Score > 0 {
+ entry.Rank = 1
+ return []RankEntry{entry}, entry, nil
+ }
+ return nil, entry, nil
+}
+func (s *Service) rank(ctx command.Context, v *state, season uint64) ([]byte, error) {
+ if season == 0 || season > v.Season {
+ return nil, fail("invalid ranking season")
+ }
+ top, mine, e := s.rankings(ctx, v, season)
+ if e != nil {
+ return nil, e
+ }
+ var out []byte
+ for _, a := range top {
+ out = wire.AppendBytes(out, 1, rankWire(a))
+ }
+ return wire.AppendBytes(out, 2, rankWire(mine)), nil
+}
+func (s *Service) seasonReward(ctx command.Context, v *state, key string) ([]byte, error) {
+ var season uint64
+ for id, r := range v.Seasons {
+ if s.seasonSettled(id, v.Season) && !r.Claimed && r.Score > 0 && (season == 0 || id < season) {
+ season = id
+ }
+ }
+ if season == 0 {
+ return nil, fail("no completed season reward")
+ }
+ total := v.Seasons[season].Score
+ var e error
+ if s.options.Ranking != nil {
+ total, e = s.options.Ranking.Total(ctx, season)
+ if e != nil {
+ return nil, e
+ }
+ }
+ var grants []gamedata.Reward
+ for _, id := range s.design.Rewards.Groups[0] {
+ rule := s.design.Rewards.Row(0, id)
+ if float64(total) >= rule.D(5) {
+ grants = append(grants, rewards(rule, 4, 3, 2)...)
+ }
+ }
+ bundle, e := s.options.Economy.Apply(ctx, key, nil, grants)
+ if e != nil {
+ return nil, e
+ }
+ r := v.Seasons[season]
+ r.Claimed = true
+ v.Seasons[season] = r
+ _, mine, e := s.rankings(ctx, v, season)
+ if e != nil {
+ return nil, e
+ }
+ return wire.AppendBytes(wire.AppendVarint(nil, 1, mine.Rank), 2, bundle), nil
+}
+
+func (s *Service) seasonSettled(id, current uint64) bool {
+ if s.options.SeasonSettled != nil {
+ return s.options.SeasonSettled(id)
+ }
+ return id < current
+}
diff --git a/go/internal/server/domain/battle/roguelike/protocol.go b/go/internal/server/domain/battle/roguelike/protocol.go
new file mode 100644
index 0000000..eda1ba1
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/protocol.go
@@ -0,0 +1,83 @@
+package roguelike
+
+import "bd2server/internal/server/protocol/wire"
+
+func stateWire(r *run) []byte {
+ if r == nil {
+ return wire.AppendVarint(nil, 1, 0)
+ }
+ b := wire.AppendVarint(nil, 1, r.Floor)
+ b = wire.AppendVarint(b, 2, r.Room)
+ return wire.AppendVarint(b, 3, r.State)
+}
+func roomWire(r room) []byte {
+ b := wire.AppendVarint(nil, 1, r.Number)
+ b = wire.AppendVarint(b, 2, r.Group)
+ b = wire.AppendVarint(b, 3, r.ID)
+ if r.Clear {
+ b = wire.AppendVarint(b, 4, 1)
+ }
+ return b
+}
+func floorWire(f floor) []byte {
+ b := wire.AppendVarint(nil, 1, f.Number)
+ for _, r := range f.Rooms {
+ b = wire.AppendBytes(b, 2, roomWire(r))
+ }
+ return b
+}
+func choiceWire(r *run) []byte {
+ if r == nil || r.ChoiceType == 0 {
+ return nil
+ }
+ b := wire.AppendVarint(nil, 1, r.ChoiceType)
+ for _, id := range r.Choice {
+ b = wire.AppendVarint(b, 2, id)
+ }
+ return b
+}
+func charWire(c character, level uint64) []byte {
+ b := wire.AppendVarint(nil, 1, c.Index)
+ b = wire.AppendVarint(b, 2, c.ID)
+ b = wire.AppendVarint(b, 3, c.HP)
+ b = wire.AppendVarint(b, 4, level)
+ return wire.AppendVarint(b, 7, c.Costume)
+}
+func costumeWire(c costume) []byte {
+ b := wire.AppendVarint(nil, 1, c.Index)
+ b = wire.AppendVarint(b, 2, c.ID)
+ b = wire.AppendVarint(b, 3, c.Level)
+ b = wire.AppendVarint(b, 4, c.Character)
+ return wire.AppendVarint(b, 10, c.Burst)
+}
+func relicWire(r relic) []byte { return wire.AppendVarint(wire.AppendVarint(nil, 1, r.Index), 2, r.ID) }
+func shopWire(r *run, price uint64) []byte {
+ b := wire.AppendVarint(nil, 2, price)
+ for _, o := range r.Shop {
+ x := wire.AppendVarint(nil, 1, o.Type)
+ x = wire.AppendVarint(x, 2, o.ID)
+ x = wire.AppendVarint(x, 3, o.Price)
+ if o.Sold {
+ x = wire.AppendVarint(x, 4, 1)
+ }
+ b = wire.AppendBytes(b, 1, x)
+ }
+ return b
+}
+func eventWire(r *run) []byte {
+ return wire.AppendVarint(wire.AppendVarint(nil, 1, r.EventGroup), 2, r.EventID)
+}
+func deckWire(b []byte, f int, r *run) []byte {
+ for _, d := range r.Deck {
+ b = wire.AppendBytes(b, f, d)
+ }
+ return b
+}
+func clearedResponse(r *run, f uint64, room *room, sf, ff, rf int) []byte {
+ b := wire.AppendBytes(nil, sf, stateWire(r))
+ if f > 0 && room != nil {
+ b = wire.AppendVarint(b, ff, f)
+ b = wire.AppendBytes(b, rf, roomWire(*room))
+ }
+ return b
+}
diff --git a/go/internal/server/domain/battle/roguelike/relic_effects.go b/go/internal/server/domain/battle/roguelike/relic_effects.go
new file mode 100644
index 0000000..cbd22c0
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/relic_effects.go
@@ -0,0 +1,26 @@
+package roguelike
+
+func (s *Service) systemEffect(r *run, typ uint64) float64 {
+ if typ == 0 {
+ return 0
+ }
+ var value float64
+ for _, item := range r.Relics {
+ for _, id := range s.design.Relics.Row(0, item.ID).A(3) {
+ buff := s.design.Buffs.Row(0, id)
+ if buff.V(6) == typ {
+ value += buff.D(7)
+ }
+ }
+ }
+ return value
+}
+func bonusGoldType(room uint64) uint64 {
+ switch room {
+ case 1:
+ return 4
+ case 2:
+ return 5
+ }
+ return 0
+}
diff --git a/go/internal/server/domain/battle/roguelike/run.go b/go/internal/server/domain/battle/roguelike/run.go
new file mode 100644
index 0000000..1a9be10
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/run.go
@@ -0,0 +1,490 @@
+package roguelike
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "math"
+ "slices"
+)
+
+func (s *Service) total(ctx command.Context, v *state) (uint64, error) {
+ if s.options.Ranking != nil {
+ if pending, ok := s.options.Ranking.(interface {
+ PendingTotal(command.Context, uint64, RankEntry) (uint64, error)
+ }); ok {
+ return pending.PendingTotal(ctx, v.Season, RankEntry{Owner: s.options.Owner, Score: v.Seasons[v.Season].Score})
+ }
+ return s.options.Ranking.Total(ctx, v.Season)
+ }
+ return v.Seasons[v.Season].Score, nil
+}
+func (s *Service) info(ctx command.Context, v *state, p Period) ([]byte, error) {
+ b := wire.AppendBytes(nil, 1, stateWire(v.Run))
+ if r := v.Run; r != nil {
+ b = wire.AppendVarint(b, 2, r.Level)
+ for _, f := range r.Floors {
+ b = wire.AppendBytes(b, 3, floorWire(f))
+ }
+ b = deckWire(b, 4, r)
+ for _, c := range r.Characters {
+ b = wire.AppendBytes(b, 5, charWire(c, s.design.Default.V(7)))
+ }
+ for _, c := range r.Costumes {
+ b = wire.AppendBytes(b, 6, costumeWire(c))
+ }
+ for _, a := range r.Relics {
+ b = wire.AppendBytes(b, 7, relicWire(a))
+ }
+ b = wire.AppendBytes(b, 8, choiceWire(r))
+ b = wire.AppendVarint(b, 9, r.Reroll)
+ b = wire.AppendBytes(b, 13, eventWire(r))
+ b = wire.AppendBytes(b, 14, shopWire(r, s.shopPrice(r)))
+ b = wire.AppendVarint(b, 15, r.BattleLevel)
+ b = wire.AppendVarint(b, 18, r.Gold)
+ }
+ keys := make([]uint64, 0, len(v.Growth))
+ for typ := range v.Growth {
+ keys = append(keys, typ)
+ }
+ slices.Sort(keys)
+ for _, typ := range keys {
+ x := wire.AppendVarint(nil, 1, typ)
+ x = wire.AppendVarint(x, 2, v.Growth[typ])
+ b = wire.AppendBytes(b, 12, x)
+ }
+ b = wire.AppendVarint(b, 16, v.MaxTry)
+ b = wire.AppendVarint(b, 17, v.Obsidian)
+ b = wire.AppendVarint(b, 19, v.Season)
+ b = wire.AppendVarint(b, 20, p.Regular)
+ for season, r := range v.Seasons {
+ if s.seasonSettled(season, v.Season) && r.Score > 0 && !r.Claimed {
+ b = wire.AppendVarint(b, 21, 1)
+ break
+ }
+ }
+ b = wire.AppendVarint(b, 22, v.MaxReward)
+ return wire.AppendVarint(b, 23, v.HighestCrystal), nil
+}
+func (s *Service) enter(ctx command.Context, v *state, p Period, level uint64, key string) ([]byte, error) {
+ l := s.design.Levels.Row(0, level)
+ if !p.Active || v.Run != nil || l.Values == nil || level > v.MaxTry+1 {
+ return nil, fail("difficulty unavailable")
+ }
+ r := &run{ID: v.NextRun, Level: level, Floor: 1, State: 8, Gold: l.V(15), Reroll: s.design.Default.V(44), Remaining: s.design.Default.V(42), ChoiceType: 1}
+ v.NextRun++
+ growth := s.design.Growth.Row(8, v.Growth[8])
+ r.Reroll += uint64(growth.D(6))
+ for f := uint64(1); f <= l.V(4); f++ {
+ rule := s.design.Floors.Row(level, f)
+ if rule.Values == nil {
+ return nil, fail("missing floor template")
+ }
+ count := uint64(3)
+ if f%2 == 0 {
+ count = 4
+ }
+ if slices.Contains(l.A(1), f) {
+ count = 1
+ }
+ fl := floor{Number: f}
+ for num := uint64(1); num <= count; num++ {
+ group, e := s.weighted(rule.A(11), rule.A(12))
+ if e != nil {
+ return nil, e
+ }
+ ids := s.design.Rooms.Groups[group]
+ if len(ids) == 0 {
+ return nil, fail("empty room group")
+ }
+ id := ids[s.sample(uint64(len(ids)))]
+ fl.Rooms = append(fl.Rooms, room{Number: num, Group: group, ID: id})
+ }
+ for _, required := range []struct{ typ, count uint64 }{{6, rule.V(13)}, {4, rule.V(14)}} {
+ var group uint64
+ for _, g := range rule.A(11) {
+ ids := s.design.Rooms.Groups[g]
+ if len(ids) > 0 && s.design.Rooms.Row(g, ids[0]).V(10) == required.typ {
+ group = g
+ break
+ }
+ }
+ if required.count > 0 && group == 0 {
+ return nil, fail("required room pool unavailable")
+ }
+ for i := uint64(0); i < required.count; i++ {
+ at := uint64(len(fl.Rooms)) - 1 - i
+ if i >= uint64(len(fl.Rooms)) {
+ return nil, fail("required rooms exceed map")
+ }
+ ids := s.design.Rooms.Groups[group]
+ fl.Rooms[at].Group = group
+ fl.Rooms[at].ID = ids[s.sample(uint64(len(ids)))]
+ }
+ }
+ r.Floors = append(r.Floors, fl)
+ }
+ if e := s.newChoice(r, 1, 0, true); e != nil {
+ return nil, e
+ }
+ if e := s.options.Tickets(ctx, key, s.design.Default.V(30)); e != nil {
+ return nil, e
+ }
+ v.Run = r
+ var b []byte
+ for _, f := range r.Floors {
+ b = wire.AppendBytes(b, 1, floorWire(f))
+ }
+ b = wire.AppendBytes(b, 2, choiceWire(r))
+ b = wire.AppendBytes(b, 3, stateWire(r))
+ b = wire.AppendVarint(b, 4, r.Gold)
+ return wire.AppendVarint(b, 5, r.Reroll), nil
+}
+func (s *Service) weighted(ids, weights []uint64) (uint64, error) {
+ if len(ids) == 0 || len(ids) != len(weights) {
+ return 0, fail("invalid weighted pool")
+ }
+ var total uint64
+ for _, w := range weights {
+ if total > math.MaxUint64-w {
+ return 0, fail("weight overflow")
+ }
+ total += w
+ }
+ if total == 0 {
+ return 0, fail("empty weighted pool")
+ }
+ roll := s.sample(total)
+ for i, w := range weights {
+ if roll < w {
+ return ids[i], nil
+ }
+ roll -= w
+ }
+ return 0, fail("invalid random sample")
+}
+func (s *Service) current(r *run) (*room, gamedata.RogueRule) {
+ if r.Floor == 0 || r.Floor > uint64(len(r.Floors)) {
+ return nil, gamedata.RogueRule{}
+ }
+ for i := range r.Floors[r.Floor-1].Rooms {
+ x := &r.Floors[r.Floor-1].Rooms[i]
+ if x.Number == r.Room {
+ return x, s.design.Rooms.Row(x.Group, x.ID)
+ }
+ }
+ return nil, gamedata.RogueRule{}
+}
+func (s *Service) roomEnter(v *state, number uint64) ([]byte, error) {
+ r := v.Run
+ if r.State != 0 || r.Floor == 0 || r.Floor > uint64(len(r.Floors)) {
+ return nil, fail("room unavailable")
+ }
+ var found *room
+ for i := range r.Floors[r.Floor-1].Rooms {
+ x := &r.Floors[r.Floor-1].Rooms[i]
+ if x.Number == number && !x.Clear && x.Group > 0 {
+ found = x
+ break
+ }
+ }
+ if found == nil {
+ return nil, fail("unknown room")
+ }
+ bosses := s.design.Default.A(2)
+ connected := r.Floor == 1 || slices.Contains(bosses, r.Floor) || slices.Contains(bosses, r.Floor-1)
+ if !connected {
+ for _, prev := range r.Floors[r.Floor-2].Rooms {
+ if prev.Clear && (prev.Number == number || (r.Floor%2 == 1 && prev.Number+1 == number) || (r.Floor%2 == 0 && prev.Number == number+1)) {
+ connected = true
+ }
+ }
+ }
+ if !connected {
+ return nil, fail("room is disconnected")
+ }
+ gain := uint64(float64(r.Gold)*(s.design.Default.D(27)+s.systemEffect(r, 2))) + uint64(s.systemEffect(r, 7))
+ if r.Floor == 1 {
+ gain = 0
+ }
+ r.Gold += gain
+ r.Room = number
+ r.EventGroup = 0
+ r.EventID = 0
+ r.Choice = nil
+ r.ChoiceType = 0
+ r.Shop = nil
+ r.ShopRoll = 0
+ rule := s.design.Rooms.Row(found.Group, found.ID)
+ fl := s.design.Floors.Row(r.Level, r.Floor)
+ switch rule.V(10) {
+ case 1, 2, 3:
+ r.State = 3
+ min, max := 10, 9
+ if rule.V(10) == 2 {
+ min, max = 4, 3
+ }
+ if rule.V(10) == 3 {
+ min, max = 2, 1
+ }
+ r.BattleLevel = fl.V(min) + s.sample(fl.V(max)-fl.V(min)+1)
+ case 4:
+ r.State = 2
+ r.Remaining = 1
+ if e := s.newChoice(r, 2, rule.V(8), false); e != nil {
+ return nil, e
+ }
+ case 5:
+ r.State = 5
+ groups := s.design.EventChoices.Row(0, rule.V(5)).A(1)
+ if len(groups) == 0 {
+ return nil, fail("missing event choices")
+ }
+ r.EventGroup = groups[s.sample(uint64(len(groups)))]
+ ids := s.design.Events.Groups[r.EventGroup]
+ if len(ids) == 0 {
+ return nil, fail("empty event group")
+ }
+ r.EventID = ids[s.sample(uint64(len(ids)))]
+ r.BattleLevel = fl.V(6) + s.sample(fl.V(5)-fl.V(6)+1)
+ case 6:
+ r.State = 4
+ if e := s.newShop(v); e != nil {
+ return nil, e
+ }
+ default:
+ return nil, fail("invalid room type")
+ }
+ b := wire.AppendBytes(nil, 1, stateWire(r))
+ b = wire.AppendBytes(b, 2, choiceWire(r))
+ if r.State == 5 {
+ b = wire.AppendBytes(b, 3, eventWire(r))
+ }
+ if r.State == 4 {
+ b = wire.AppendBytes(b, 4, shopWire(r, s.shopPrice(r)))
+ }
+ b = wire.AppendVarint(b, 6, gain)
+ return wire.AppendVarint(b, 5, r.BattleLevel), nil
+}
+func (s *Service) clearRoom(r *run) (uint64, *room) {
+ f := r.Floor
+ rm, _ := s.current(r)
+ var result *room
+ if rm != nil {
+ rm.Clear = true
+ x := *rm
+ result = &x
+ r.Cleared++
+ }
+ r.Floor++
+ r.State = 0
+ r.ChoiceType = 0
+ r.Choice = nil
+ r.Remaining = 0
+ r.Shop = nil
+ r.EventGroup = 0
+ r.EventID = 0
+ return f, result
+}
+func (s *Service) newChoice(r *run, typ, choice uint64, wild bool) error {
+ r.ChoiceType = typ
+ r.RelicChoice = choice
+ r.Choice = nil
+ if typ == 1 {
+ initial := wild || r.Room == 0
+ pool := s.costumePool(r, initial)
+ if wild {
+ r.Choice = pool
+ return nil
+ }
+ for _, field := range []int{8, 9, 10, 11} {
+ id, remaining, ok := s.pickCostume(r, pool, s.design.Default.V(field), initial)
+ if !ok {
+ break
+ }
+ r.Choice = append(r.Choice, id)
+ pool = remaining
+ }
+ } else if typ == 2 {
+ rule := s.design.RelicChoices.Row(0, choice)
+ if rule.Values == nil {
+ return fail("missing relic pool")
+ }
+ for len(r.Choice) < 3 {
+ id, e := s.rollRelic(r, rule, r.Choice)
+ if e != nil {
+ break
+ }
+ r.Choice = append(r.Choice, id)
+ }
+ }
+ if len(r.Choice) == 0 {
+ return fail("no eligible choice")
+ }
+ return nil
+}
+func (s *Service) rollRelic(r *run, choice gamedata.RogueRule, exclude []uint64) (uint64, error) {
+ var grades, weights []uint64
+ for i, w := range choice.A(2) {
+ if w > 0 {
+ grades = append(grades, uint64(i))
+ weights = append(weights, w)
+ }
+ }
+ grade, e := s.weighted(grades, weights)
+ if e != nil {
+ return 0, e
+ }
+ var ids []uint64
+ for _, id := range s.design.Relics.Groups[0] {
+ a := s.design.Relics.Row(0, id)
+ if a.V(1) != grade || choice.V(3) != 0 && a.V(9) != choice.V(3) || slices.Contains(exclude, id) {
+ continue
+ }
+ owned := false
+ for _, item := range r.Relics {
+ if item.ID == id {
+ owned = true
+ }
+ }
+ if !owned {
+ ids = append(ids, id)
+ }
+ }
+ if len(ids) == 0 {
+ return 0, fail("relic pool exhausted")
+ }
+ return ids[s.sample(uint64(len(ids)))], nil
+}
+func (s *Service) addCostume(ctx command.Context, v *state, id uint64) (*character, *costume, error) {
+ r := v.Run
+ d, ok := s.design.Costumes[id]
+ if !ok {
+ return nil, nil, fail("invalid costume")
+ }
+ for i := range r.Costumes {
+ c := &r.Costumes[i]
+ if c.ID == id {
+ if c.Level >= d.MaxLevel {
+ return nil, nil, fail("costume at maximum")
+ }
+ c.Level++
+ return nil, c, nil
+ }
+ }
+ var char *character
+ for i := range r.Characters {
+ if r.Characters[i].Unique == d.Unique {
+ char = &r.Characters[i]
+ break
+ }
+ }
+ if char == nil {
+ hp := d.Health
+ growth := s.design.Growth.Row(1, v.Growth[1])
+ hp = uint64(float64(hp) * (1 + growth.D(6)))
+ if s.options.Health != nil {
+ var e error
+ hp, e = s.options.Health(ctx, d, growth.D(6))
+ if e != nil {
+ return nil, nil, e
+ }
+ }
+ r.Characters = append(r.Characters, character{Index: s.index(v), ID: d.Character, Unique: d.Unique, HP: hp, MaxHP: hp})
+ char = &r.Characters[len(r.Characters)-1]
+ }
+ c := costume{Index: s.index(v), ID: id, Character: char.Index}
+ r.Costumes = append(r.Costumes, c)
+ if char.Costume == 0 {
+ char.Costume = c.Index
+ }
+ return char, &r.Costumes[len(r.Costumes)-1], nil
+}
+func (s *Service) addRelic(v *state, id uint64) (relic, error) {
+ if s.design.Relics.Row(0, id).Values == nil {
+ return relic{}, fail("unknown relic")
+ }
+ for _, r := range v.Run.Relics {
+ if r.ID == id {
+ return relic{}, fail("relic already owned")
+ }
+ }
+ r := relic{s.index(v), id}
+ v.Run.Relics = append(v.Run.Relics, r)
+ for _, buffID := range s.design.Relics.Row(0, id).A(3) {
+ buff := s.design.Buffs.Row(0, buffID)
+ if buff.V(6) == 8 {
+ v.Run.Gold += uint64(buff.D(7))
+ }
+ if buff.V(6) == 10 {
+ v.Run.Reroll += uint64(buff.D(7))
+ }
+ }
+ return r, nil
+}
+func (s *Service) selectReward(ctx command.Context, v *state, typ, id uint64) ([]byte, error) {
+ r := v.Run
+ beforeGold := r.Gold
+ if typ == 3 && r.State == 1 && r.Room > 0 {
+ _, rule := s.current(r)
+ rate := rule.D(2)
+ if rate <= 0 {
+ return nil, fail("healing choice unavailable")
+ }
+ var b []byte
+ for i := range r.Characters {
+ c := &r.Characters[i]
+ if c.HP > 0 {
+ c.HP = min(c.MaxHP, c.HP+uint64(float64(c.MaxHP)*rate))
+ }
+ b = wire.AppendBytes(b, 3, charWire(*c, s.design.Default.V(7)))
+ }
+ f, rm := s.clearRoom(r)
+ return append(b, clearedResponse(r, f, rm, 1, 6, 7)...), nil
+ }
+ if (r.State != 1 && r.State != 2 && r.State != 8) || typ != r.ChoiceType || !slices.Contains(r.Choice, id) {
+ return nil, fail("reward was not offered")
+ }
+ var b []byte
+ if typ == 1 {
+ c, a, e := s.addCostume(ctx, v, id)
+ if e != nil {
+ return nil, e
+ }
+ if c != nil {
+ b = wire.AppendBytes(b, 3, charWire(*c, s.design.Default.V(7)))
+ }
+ b = wire.AppendBytes(b, 4, costumeWire(*a))
+ } else {
+ a, e := s.addRelic(v, id)
+ if e != nil {
+ return nil, e
+ }
+ b = wire.AppendBytes(b, 5, relicWire(a))
+ }
+ if r.Remaining > 0 {
+ r.Remaining--
+ }
+ var f uint64
+ var room *room
+ if r.Remaining > 0 {
+ r.State = 1
+ wild := uint64(len(r.Costumes)) < s.design.Default.V(45)
+ if wild {
+ r.State = 8
+ }
+ if e := s.newChoice(r, typ, r.RelicChoice, wild); e != nil {
+ return nil, e
+ }
+ } else if r.Room == 0 {
+ r.State = 0
+ r.ChoiceType = 0
+ r.Choice = nil
+ } else {
+ f, room = s.clearRoom(r)
+ }
+ b = append(b, clearedResponse(r, f, room, 1, 6, 7)...)
+ b = wire.AppendBytes(b, 2, choiceWire(r))
+ b = wire.AppendVarint(b, 8, r.Gold-beforeGold)
+ return wire.AppendVarint(b, 9, r.Reroll), nil
+}
diff --git a/go/internal/server/domain/battle/roguelike/service.go b/go/internal/server/domain/battle/roguelike/service.go
new file mode 100644
index 0000000..dd7e022
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/service.go
@@ -0,0 +1,321 @@
+package roguelike
+
+import (
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/battle"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+ "crypto/sha256"
+ "encoding/json"
+ "fmt"
+ "math"
+ "math/rand/v2"
+ "slices"
+ "strings"
+)
+
+type Economy interface {
+ Apply(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error)
+}
+type Period struct {
+ Season, Regular uint64
+ Active bool
+}
+type RankEntry struct {
+ Owner, Score, Damage, Rank uint64
+ Profile []byte
+}
+type RankPublication struct {
+ Account string
+ Season, Version uint64
+ Entry RankEntry
+}
+type Ranking interface {
+ Snapshot(command.Context, uint64, RankEntry) ([]RankEntry, RankEntry, error)
+ Total(command.Context, uint64) (uint64, error)
+}
+type Options struct {
+ Access func(command.Context) error
+ Economy Economy
+ Period func(command.Context) (Period, error)
+ Tickets func(command.Context, string, uint64) error
+ CostumeVisible func(uint64) bool
+ CostumeOwned func(uint64) bool
+ SeasonSettled func(uint64) bool
+ Health func(command.Context, gamedata.RogueCostume, float64) (uint64, error)
+ Evidence func(command.Context) battle.SettlementEvidence
+ Ranking Ranking
+ Publish func(command.Context, uint64, uint64, uint64, uint64) error
+ Owner uint64
+}
+type Service struct {
+ store stateio.Store
+ design *gamedata.RogueLikeDesign
+ options Options
+ sample func(uint64) uint64
+}
+type room struct {
+ Number, Group, ID uint64
+ Clear bool
+}
+type floor struct {
+ Number uint64
+ Rooms []room
+}
+type character struct{ Index, ID, Unique, HP, MaxHP, Costume uint64 }
+type costume struct{ Index, ID, Character, Level, Burst uint64 }
+type relic struct{ Index, ID uint64 }
+type offer struct {
+ Type, ID, Price uint64
+ Sold bool
+}
+type run struct {
+ ID, Level uint64
+ Floor, Room, State uint64
+ Gold, Reroll, ShopRoll uint64
+ Remaining, ChoiceType, RelicChoice uint64
+ EventGroup, EventID, PendingRelic uint64
+ BattleLevel, EncounterMode uint64
+ Events, Elites, Bosses, Cleared, Crystal uint64
+ Floors []floor
+ Choice []uint64
+ Characters []character
+ Costumes []costume
+ Relics []relic
+ Deck [][]byte
+ Shop []offer
+ Encounter string
+ ChangedParticipants []uint64
+ DeferredEffects []uint64
+}
+type seasonRecord struct {
+ Score, Damage uint64
+ Claimed bool
+}
+type state struct {
+ Version string
+ Season, Regular, NextIndex, NextRun, MaxTry, MaxReward, Obsidian, HighestCrystal uint64
+ Growth map[uint64]uint64
+ Seasons map[uint64]seasonRecord
+ Run *run
+ LastScore []byte
+}
+type receipt struct {
+ Digest [32]byte
+ Reply []byte
+}
+
+func Open(store stateio.Store, d *gamedata.RogueLikeDesign, o Options) (*Service, error) {
+ if store == nil || d == nil || o.Economy == nil || o.Period == nil || o.Tickets == nil || o.Access == nil {
+ return nil, fmt.Errorf("roguelike: missing dependency")
+ }
+ return &Service{store: store, design: d, options: o, sample: func(n uint64) uint64 {
+ if n == 0 {
+ return 0
+ }
+ return rand.Uint64N(n)
+ }}, nil
+}
+func (s *Service) load(ctx command.Context) (*state, Period, error) {
+ p, e := s.options.Period(ctx)
+ if e != nil {
+ return nil, p, e
+ }
+ if p.Season == 0 {
+ return nil, p, fmt.Errorf("roguelike: missing season")
+ }
+ v := &state{Version: versionconfig.State(), Season: p.Season, Regular: p.Regular, NextIndex: 1, NextRun: 1, Growth: map[uint64]uint64{}, Seasons: map[uint64]seasonRecord{}}
+ raw, e := s.store.Load(ctx.State, "roguelike")
+ if e != nil {
+ return nil, p, e
+ }
+ if raw != nil {
+ if e = stateio.RequireExactJSONObject(raw, "Version", "Season", "Regular", "NextIndex", "NextRun", "MaxTry", "MaxReward", "Obsidian", "HighestCrystal", "Growth", "Seasons", "Run", "LastScore"); e != nil {
+ return nil, p, e
+ }
+ if e = json.Unmarshal(raw, v); e != nil {
+ return nil, p, e
+ }
+ if v.Version != versionconfig.State() || v.NextIndex == 0 || v.NextRun == 0 || v.Growth == nil || v.Seasons == nil {
+ return nil, p, fmt.Errorf("roguelike: invalid state")
+ }
+ }
+ if v.Season != p.Season {
+ v.Season = p.Season
+ v.Regular = p.Regular
+ v.Run = nil
+ v.Growth = map[uint64]uint64{}
+ v.Obsidian = s.design.Default.V(35)
+ v.MaxReward = 0
+ v.MaxTry = 0
+ v.HighestCrystal = 0
+ }
+ return v, p, nil
+}
+func (s *Service) save(ctx command.Context, v *state) error {
+ b, e := json.Marshal(v)
+ if e != nil {
+ return e
+ }
+ return s.store.Save(ctx.State, "roguelike", b)
+}
+func n(b []byte, f int) uint64 { v, _, _ := wire.Varint(b, f); return v }
+func messages(b []byte, f int) (a [][]byte, e error) {
+ e = wire.Walk(b, func(x wire.Field) error {
+ if x.Number == f {
+ if x.Type != 2 {
+ return wire.ErrMalformed
+ }
+ a = append(a, slices.Clone(x.Value))
+ }
+ return nil
+ })
+ return
+}
+func (s *Service) index(v *state) uint64 { i := v.NextIndex; v.NextIndex++; return i }
+func fail(message string) error { return fmt.Errorf("roguelike: %s", message) }
+
+var routes = map[string]int{
+ "Info": 279, "Enter": 280, "RoomEnter": 282, "SelectReward": 283, "EventSelect": 318, "EventChoice": 319, "GiveUp": 281, "GiveUpInfo": 324, "ShopBuy": 320, "ShopReRoll": 321, "ShopExit": 322, "CostumeUpgrade": 342, "CostumeBurstUpgrade": 652, "Growth": 323, "AllUserScoreInfo": 325, "RankInfo": 326, "SeasonReward": 327, "QuickBattle": 340, "RelicMix": 347, "RewardReRoll": 284, "DeckSave": 285, "BattleCharChange": 317, "BattleEndPreview": 466,
+}
+
+func (s *Service) Handle(ctx command.Context, path string, b []byte) (int, []byte, bool, error) {
+ op := strings.TrimPrefix(path, "/EvilCastleRogueLike")
+ code, ok := routes[op]
+ if !ok || op == path {
+ return 0, nil, false, nil
+ }
+ seq := n(b, 1)
+ if seq == 0 || seq > math.MaxInt32 {
+ return code, nil, true, fail("invalid sequence")
+ }
+ if e := wire.Walk(b, func(wire.Field) error { return nil }); e != nil {
+ return code, nil, true, e
+ }
+ query := op == "Info" || op == "GiveUpInfo" || op == "RankInfo" || op == "AllUserScoreInfo" || op == "BattleEndPreview"
+ key := fmt.Sprintf("%s:%s:%d", ctx.SessionID, op, seq)
+ digest := sha256.Sum256(b)
+ if !query {
+ raw, found, e := ctx.State.LoadEntry("battle", "rogue_replies", key)
+ if e != nil {
+ return code, nil, true, e
+ }
+ if found {
+ var r receipt
+ if json.Unmarshal(raw, &r) != nil || r.Digest != digest {
+ return code, nil, true, fail("changed retry")
+ }
+ return code, r.Reply, true, nil
+ }
+ }
+ v, p, e := s.load(ctx)
+ if e != nil {
+ return code, nil, true, e
+ }
+ out, e := s.handle(ctx, v, p, op, b, "roguelike:"+key)
+ if e != nil {
+ return code, nil, true, e
+ }
+ if e = s.save(ctx, v); e != nil {
+ return code, nil, true, e
+ }
+ if !query {
+ raw, e := json.Marshal(receipt{digest, out})
+ if e != nil {
+ return code, nil, true, e
+ }
+ if e = ctx.State.PutEntry("battle", "rogue_replies", key, raw); e != nil {
+ return code, nil, true, e
+ }
+ }
+ return code, out, true, nil
+}
+func (s *Service) handle(ctx command.Context, v *state, p Period, op string, b []byte, key string) ([]byte, error) {
+ switch op {
+ case "Info":
+ return s.info(ctx, v, p)
+ case "AllUserScoreInfo":
+ total, e := s.total(ctx, v)
+ return wire.AppendVarint(nil, 1, total), e
+ case "RankInfo":
+ return s.rank(ctx, v, n(b, 2))
+ case "SeasonReward":
+ return s.seasonReward(ctx, v, key)
+ case "Growth":
+ return s.growth(v, b)
+ case "QuickBattle":
+ if e := s.options.Access(ctx); e != nil {
+ return nil, e
+ }
+ return s.quick(ctx, v, p, b, key)
+ case "Enter":
+ if e := s.options.Access(ctx); e != nil {
+ return nil, e
+ }
+ return s.enter(ctx, v, p, n(b, 2), key)
+ case "GiveUpInfo":
+ if v.Run == nil {
+ return nil, fail("no active run")
+ }
+ _, obs := s.score(v, true)
+ return wire.AppendVarint(nil, 1, obs), nil
+ case "GiveUp":
+ if v.Run == nil {
+ return nil, fail("no active run")
+ }
+ score, _, e := s.finish(ctx, v, false, true, key)
+ return wire.AppendBytes(nil, 1, score), e
+ }
+ r := v.Run
+ if r == nil {
+ return nil, fail("no active run")
+ }
+ if !p.Active {
+ return nil, fail("season is closed")
+ }
+ switch op {
+ case "RoomEnter":
+ return s.roomEnter(v, n(b, 2))
+ case "SelectReward":
+ return s.selectReward(ctx, v, n(b, 2), n(b, 4))
+ case "RewardReRoll":
+ if r.State != 1 && r.State != 2 {
+ return nil, fail("choice cannot reroll")
+ }
+ if r.Reroll == 0 {
+ return nil, fail("no rerolls")
+ }
+ r.Reroll--
+ if e := s.newChoice(r, r.ChoiceType, r.RelicChoice, false); e != nil {
+ return nil, e
+ }
+ return wire.AppendBytes(wire.AppendVarint(nil, 1, r.Reroll), 2, choiceWire(r)), nil
+ case "ShopBuy":
+ return s.shopBuy(ctx, v, n(b, 2), n(b, 3))
+ case "ShopReRoll":
+ return s.shopReroll(v)
+ case "ShopExit":
+ if r.State != 4 {
+ return nil, fail("not in shop")
+ }
+ f, room := s.clearRoom(r)
+ return clearedResponse(r, f, room, 1, 2, 3), nil
+ case "CostumeUpgrade", "CostumeBurstUpgrade":
+ return s.upgrade(r, n(b, 2), n(b, 3), op == "CostumeBurstUpgrade")
+ case "DeckSave":
+ return s.deckSave(r, b)
+ case "BattleCharChange":
+ return s.change(ctx, r, n(b, 2), n(b, 3))
+ case "RelicMix":
+ return s.mix(v, b)
+ case "EventSelect":
+ return s.eventSelect(v, n(b, 2))
+ case "EventChoice":
+ return s.eventChoice(v, n(b, 2), n(b, 3))
+ case "BattleEndPreview":
+ return s.preview(ctx, v, b)
+ }
+ return nil, fail("unknown operation")
+}
diff --git a/go/internal/server/domain/battle/roguelike/shop_roster.go b/go/internal/server/domain/battle/roguelike/shop_roster.go
new file mode 100644
index 0000000..49aa5ea
--- /dev/null
+++ b/go/internal/server/domain/battle/roguelike/shop_roster.go
@@ -0,0 +1,330 @@
+package roguelike
+
+import (
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "encoding/binary"
+ "math"
+ "slices"
+)
+
+func (s *Service) shopPrice(r *run) uint64 {
+ _, rule := s.current(r)
+ shop := s.design.Shops.Row(0, rule.V(9))
+ return shop.V(5) + r.ShopRoll*shop.V(3)
+}
+func (s *Service) newShop(v *state) error {
+ r := v.Run
+ _, rule := s.current(r)
+ d := s.design.Shops.Row(0, rule.V(9))
+ if d.Values == nil {
+ return fail("missing shop")
+ }
+ r.Shop = nil
+ pool := s.costumePool(r, false)
+ for _, option := range d.A(1) {
+ id, remaining, ok := s.pickCostume(r, pool, option, false)
+ if !ok {
+ break
+ }
+ r.Shop = append(r.Shop, offer{Type: 1, ID: id, Price: s.design.Default.V(36)})
+ pool = remaining
+ }
+ var selected []uint64
+ for i := uint64(0); i < d.V(7); i++ {
+ id, e := s.rollRelic(r, s.design.RelicChoices.Row(0, d.V(6)), selected)
+ if e != nil {
+ break
+ }
+ selected = append(selected, id)
+ r.Shop = append(r.Shop, offer{Type: 2, ID: id, Price: s.design.Relics.Row(0, id).V(8)})
+ }
+ r.Shop = append(r.Shop, offer{Type: 3, ID: 0, Price: s.design.Default.V(38)})
+ discount := s.design.Levels.Row(0, r.Level).D(12) + s.design.Growth.Row(6, v.Growth[6]).D(6)
+ for i := range r.Shop {
+ if s.sample(10000) < uint64(discount*10000) {
+ r.Shop[i].Price = uint64(float64(r.Shop[i].Price) * (1 - s.design.Default.D(37)))
+ }
+ }
+ return nil
+}
+func (s *Service) shopBuy(ctx command.Context, v *state, typ, id uint64) ([]byte, error) {
+ r := v.Run
+ beforeGold := r.Gold
+ if r.State != 4 {
+ return nil, fail("not in shop")
+ }
+ var selected *offer
+ for i := range r.Shop {
+ o := &r.Shop[i]
+ if o.Type == typ && o.ID == id && !o.Sold {
+ selected = o
+ break
+ }
+ }
+ if selected == nil || selected.Price > r.Gold {
+ return nil, fail("offer unavailable or insufficient gold")
+ }
+ var b []byte
+ switch typ {
+ case 1:
+ c, a, e := s.addCostume(ctx, v, id)
+ if e != nil {
+ return nil, e
+ }
+ if c != nil {
+ b = wire.AppendBytes(b, 1, charWire(*c, s.design.Default.V(7)))
+ }
+ b = wire.AppendBytes(b, 2, costumeWire(*a))
+ case 2:
+ a, e := s.addRelic(v, id)
+ if e != nil {
+ return nil, e
+ }
+ b = wire.AppendBytes(b, 3, relicWire(a))
+ case 3:
+ changed := false
+ for i := range r.Characters {
+ c := &r.Characters[i]
+ if c.HP < c.MaxHP {
+ c.HP = min(c.MaxHP, c.HP+c.MaxHP*s.design.Default.V(39)/100)
+ changed = true
+ b = wire.AppendBytes(b, 1, charWire(*c, s.design.Default.V(7)))
+ }
+ }
+ if !changed {
+ return nil, fail("no character needs healing")
+ }
+ default:
+ return nil, fail("unknown shop item")
+ }
+ r.Gold -= selected.Price
+ selected.Sold = true
+ b = wire.AppendVarint(b, 4, uint64(int64(r.Gold)-int64(beforeGold)))
+ return wire.AppendVarint(b, 5, r.Reroll), nil
+}
+func (s *Service) shopReroll(v *state) ([]byte, error) {
+ r := v.Run
+ if r.State != 4 {
+ return nil, fail("not in shop")
+ }
+ price := s.shopPrice(r)
+ if r.Gold < price {
+ return nil, fail("insufficient shop gold")
+ }
+ r.Gold -= price
+ r.ShopRoll++
+ if e := s.newShop(v); e != nil {
+ return nil, e
+ }
+ b := wire.AppendBytes(nil, 1, shopWire(r, s.shopPrice(r)))
+ return wire.AppendVarint(b, 2, uint64(-int64(price))), nil
+}
+func (s *Service) upgrade(r *run, index, count uint64, burst bool) ([]byte, error) {
+ if r.State != 4 || count == 0 || count > math.MaxInt32 {
+ return nil, fail("invalid shop upgrade")
+ }
+ for i := range r.Costumes {
+ c := &r.Costumes[i]
+ if c.Index != index {
+ continue
+ }
+ d := s.design.Costumes[c.ID]
+ current, maximum, price := c.Level, d.MaxLevel, s.design.Default.V(12)
+ if burst {
+ current, maximum, price = c.Burst, d.MaxBurst, s.design.Default.V(3)
+ }
+ if current > maximum || count > maximum-current || count > math.MaxInt32/max(price, 1) || r.Gold < count*price {
+ return nil, fail("upgrade exceeds limit or gold")
+ }
+ cost := count * price
+ r.Gold -= cost
+ if burst {
+ c.Burst += count
+ } else {
+ c.Level += count
+ }
+ return wire.AppendVarint(wire.AppendBytes(nil, 1, costumeWire(*c)), 2, uint64(-int64(cost))), nil
+ }
+ return nil, fail("costume not owned")
+}
+func (s *Service) deckSave(r *run, b []byte) ([]byte, error) {
+ if r.State == 3 || r.State == 9 || r.Encounter != "" {
+ return nil, fail("formation locked in battle")
+ }
+ entries, e := messages(b, 2)
+ if e != nil {
+ return nil, e
+ }
+ if len(entries) == 0 || len(entries) > len(r.Characters) {
+ return nil, fail("invalid formation size")
+ }
+ seen, positions, sequences := map[uint64]bool{}, map[uint64]bool{}, map[uint64]bool{}
+ var active uint64
+ for _, raw := range entries {
+ id, pos, seq := n(raw, 1), int64(n(raw, 2)), n(raw, 3)
+ var c *character
+ for i := range r.Characters {
+ if r.Characters[i].Index == id {
+ c = &r.Characters[i]
+ }
+ }
+ if c == nil || seen[id] || pos < -1 || pos > 11 || seq == 0 || seq > uint64(len(r.Characters)) {
+ return nil, fail("invalid formation member")
+ }
+ seen[id] = true
+ if pos >= 0 {
+ if c.HP == 0 || positions[uint64(pos)] || sequences[seq] {
+ return nil, fail("invalid active formation")
+ }
+ positions[uint64(pos)] = true
+ sequences[seq] = true
+ active++
+ }
+ }
+ if active == 0 || active > uint64(max(1, 5-int(s.systemEffect(r, 9)))) {
+ return nil, fail("invalid active party")
+ }
+ r.Deck = entries
+ return deckWire(nil, 1, r), nil
+}
+func (s *Service) change(ctx command.Context, r *run, in, out uint64) ([]byte, error) {
+ if r.Encounter == "" || r.State != 3 && r.State != 9 || in == out || in == 0 && out == 0 || s.options.Evidence == nil {
+ return nil, fail("no active battle change")
+ }
+ proof := s.options.Evidence(ctx)
+ if proof.Receipt != r.Encounter || proof.Round == 0 {
+ return nil, fail("change before battle start")
+ }
+ incoming, outgoing := -1, -1
+ active := 0
+ for i, d := range r.Deck {
+ if n(d, 1) == in {
+ incoming = i
+ }
+ if n(d, 1) == out {
+ outgoing = i
+ }
+ if int64(n(d, 2)) >= 0 {
+ active++
+ }
+ }
+ if out != 0 && (outgoing < 0 || int64(n(r.Deck[outgoing], 2)) < 0) {
+ return nil, fail("outgoing character not deployed")
+ }
+ if in != 0 {
+ alive := false
+ for _, c := range r.Characters {
+ if c.Index == in && c.HP > 0 {
+ alive = true
+ }
+ }
+ if !alive || incoming >= 0 && int64(n(r.Deck[incoming], 2)) >= 0 {
+ return nil, fail("incoming character not an alive reserve")
+ }
+ if out == 0 && active >= max(1, 5-int(s.systemEffect(r, 9))) {
+ return nil, fail("active party is full")
+ }
+ }
+ position, sequence := uint64(0), uint64(active+1)
+ if outgoing >= 0 {
+ position, sequence = n(r.Deck[outgoing], 2), n(r.Deck[outgoing], 3)
+ } else {
+ used := map[uint64]bool{}
+ for _, d := range r.Deck {
+ if int64(n(d, 2)) >= 0 {
+ used[n(d, 2)] = true
+ }
+ }
+ for used[position] {
+ position++
+ }
+ }
+ if outgoing >= 0 {
+ r.Deck[outgoing] = wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, out), 2, math.MaxUint64), 3, n(r.Deck[outgoing], 3))
+ }
+ if in != 0 {
+ entry := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, in), 2, position), 3, sequence)
+ if incoming < 0 {
+ r.Deck = append(r.Deck, entry)
+ } else {
+ r.Deck[incoming] = entry
+ }
+ if !slices.Contains(r.ChangedParticipants, in) {
+ r.ChangedParticipants = append(r.ChangedParticipants, in)
+ }
+ }
+ if out != 0 && !slices.Contains(r.ChangedParticipants, out) {
+ r.ChangedParticipants = append(r.ChangedParticipants, out)
+ }
+ return nil, nil
+}
+func (s *Service) mix(v *state, b []byte) ([]byte, error) {
+ r := v.Run
+ if r.State == 3 || r.State == 9 {
+ return nil, fail("cannot mix in battle")
+ }
+ var indexes []uint64
+ e := wire.Walk(b, func(f wire.Field) error {
+ if f.Number != 2 {
+ return nil
+ }
+ switch f.Type {
+ case 0:
+ x, k := binary.Uvarint(f.Value)
+ if k <= 0 {
+ return wire.ErrMalformed
+ }
+ indexes = append(indexes, x)
+ case 2:
+ for p := f.Value; len(p) > 0; {
+ x, k := binary.Uvarint(p)
+ if k <= 0 {
+ return wire.ErrMalformed
+ }
+ indexes = append(indexes, x)
+ p = p[k:]
+ }
+ default:
+ return wire.ErrMalformed
+ }
+ return nil
+ })
+ if e != nil {
+ return nil, e
+ }
+ if len(indexes) != 2 || indexes[0] == indexes[1] {
+ return nil, fail("mix requires two distinct relics")
+ }
+ var materials []relic
+ for _, a := range r.Relics {
+ if slices.Contains(indexes, a.Index) {
+ materials = append(materials, a)
+ }
+ }
+ if len(materials) != 2 {
+ return nil, fail("mix material unowned")
+ }
+ var result uint64
+ for _, id := range s.design.Mix.Groups[0] {
+ rule := s.design.Mix.Row(0, id)
+ a, b := rule.V(2), rule.V(3)
+ if materials[0].ID == a && materials[1].ID == b || materials[1].ID == a && materials[0].ID == b {
+ result = rule.V(4)
+ break
+ }
+ }
+ if result == 0 {
+ return nil, fail("no matching relic recipe")
+ }
+ add, e := s.addRelic(v, result)
+ if e != nil {
+ return nil, e
+ }
+ r.Relics = slices.DeleteFunc(r.Relics, func(a relic) bool { return slices.Contains(indexes, a.Index) })
+ out := wire.AppendBytes(nil, 1, relicWire(add))
+ for _, a := range materials {
+ out = wire.AppendBytes(out, 2, relicWire(a))
+ }
+ return wire.AppendVarint(out, 3, r.Reroll), nil
+}
diff --git a/go/internal/server/domain/battle/session.go b/go/internal/server/domain/battle/session.go
index d9da877..3b61af6 100644
--- a/go/internal/server/domain/battle/session.go
+++ b/go/internal/server/domain/battle/session.go
@@ -296,7 +296,7 @@ func (state *battleState) completion(win bool) Completion {
func (s *Service) checkpoint(state *battleState, raw []byte) error {
common := one(raw, 1)
if len(raw) > 4<<20 || value(common, 1) != state.Mode || value(common, 2) != state.Index || value(common, 3)+1 != state.Round {
- return fmt.Errorf("battle: checkpoint encounter mismatch")
+ return fmt.Errorf("battle: checkpoint encounter mismatch: bytes=%d mode=%d expected_mode=%d index=%d expected_index=%d round=%d expected_round=%d", len(raw), value(common, 1), state.Mode, value(common, 2), state.Index, value(common, 3), state.Round-1)
}
if scenario := one(raw, 103); scenario != nil {
pack := value(scenario, 3)
diff --git a/go/internal/server/domain/battle/settlement_evidence.go b/go/internal/server/domain/battle/settlement_evidence.go
new file mode 100644
index 0000000..e3c5c11
--- /dev/null
+++ b/go/internal/server/domain/battle/settlement_evidence.go
@@ -0,0 +1,17 @@
+package battle
+
+import "bd2server/internal/server/domain/command"
+
+type SettlementEvidence struct {
+ Receipt string
+ Mode, Deck, Monster, Round, Attempt uint64
+ InitialBlue [][]byte
+}
+
+func (s *Service) SettlementEvidence(ctx command.Context) SettlementEvidence {
+ v := s.stateLocked(ctx)
+ if !v.Entered {
+ return SettlementEvidence{}
+ }
+ return SettlementEvidence{v.EnterReceipt, v.Mode, v.Deck, v.Monster, v.Round, v.Attempt, v.InitialBlue}
+}
diff --git a/go/internal/server/domain/cafeteria/service.go b/go/internal/server/domain/cafeteria/service.go
new file mode 100644
index 0000000..2de4174
--- /dev/null
+++ b/go/internal/server/domain/cafeteria/service.go
@@ -0,0 +1,507 @@
+package cafeteria
+
+import (
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "math/rand/v2"
+ "slices"
+ "time"
+)
+
+type Economy interface {
+ Apply(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error)
+}
+type note struct {
+ Costume, Served uint64
+ Claimed bool
+}
+type receipt struct {
+ Digest [32]byte
+ Reply []byte
+}
+type snapshot struct {
+ Version string
+ Level, Manage uint64
+ RewardTime, SpawnTime int64
+ Facilities, Managers, Regular []uint64
+ Rewarded map[uint64]bool
+ Connection, DailyCoins uint64
+ Day string
+ Introduction bool
+ Notes map[uint64]*note
+ LastEvent, LastRare int64
+ Receipts map[string]receipt
+}
+type Service struct {
+ store stateio.Store
+ design *gamedata.CafeteriaDesign
+ economy Economy
+ state snapshot
+ now func() time.Time
+ resetSeconds int64
+ owned func() []uint64
+ hasEpisode func(uint64) bool
+}
+
+func Open(ctx command.Context, store stateio.Store, d *gamedata.CafeteriaDesign, e Economy) (*Service, error) {
+ if store == nil || d == nil || e == nil || len(d.Levels.Groups[0]) == 0 {
+ return nil, errors.New("cafeteria: missing dependency")
+ }
+ s := &Service{store: store, design: d, economy: e, now: time.Now, resetSeconds: 9 * 3600}
+ s.state = snapshot{Version: versionconfig.State(), Level: d.Levels.Groups[0][0], Rewarded: map[uint64]bool{}, Notes: map[uint64]*note{}, Receipts: map[string]receipt{}}
+ b, err := store.Load(ctx.State, "cafeteria")
+ if err != nil {
+ return nil, err
+ }
+ if b != nil {
+ if err = stateio.RequireExactJSONObject(b, "Version", "Level", "Manage", "RewardTime", "SpawnTime", "Facilities", "Managers", "Regular", "Rewarded", "Connection", "DailyCoins", "Day", "Introduction", "Notes", "LastEvent", "LastRare", "Receipts"); err != nil {
+ return nil, err
+ }
+ if err = json.Unmarshal(b, &s.state); err != nil {
+ return nil, err
+ }
+ if s.state.Version != versionconfig.State() || s.state.Rewarded == nil || s.state.Notes == nil || s.state.Receipts == nil {
+ return nil, errors.New("cafeteria: invalid state")
+ }
+ if _, ok := d.Levels.Row(0, s.state.Level); !ok {
+ return nil, errors.New("cafeteria: unknown level")
+ }
+ for id, n := range s.state.Notes {
+ if n == nil || n.Costume != id {
+ return nil, errors.New("cafeteria: invalid note")
+ }
+ }
+ } else {
+ for _, id := range d.Manage.Groups[0] {
+ r, _ := d.Manage.Row(0, id)
+ if f := r.V(4); f > 0 {
+ s.state.Facilities = append(s.state.Facilities, f)
+ }
+ if p := r.V(9); p > 0 {
+ s.state.Managers = append(s.state.Managers, p)
+ }
+ }
+ }
+ return s, nil
+}
+func (s *Service) AttachOwnedCostumes(f func() []uint64) { s.owned = f }
+func (s *Service) AttachDatingHasEpisode(f func(uint64) bool) { s.hasEpisode = f }
+func (s *Service) SetResetSeconds(v int64) { s.resetSeconds = v }
+func (s *Service) day() string {
+ return s.now().UTC().Add(time.Duration(9*3600-s.resetSeconds) * time.Second).Format("2006-01-02")
+}
+func (s *Service) save(ctx command.Context) error {
+ b, e := json.Marshal(s.state)
+ if e != nil {
+ return e
+ }
+ return s.store.Save(ctx.State, "cafeteria", b)
+}
+func (s *Service) roll() error {
+ if s.owned == nil || s.hasEpisode == nil {
+ return errors.New("cafeteria: roster or dating unavailable")
+ }
+ now := s.now().UnixMilli()
+ if s.state.RewardTime == 0 {
+ s.state.RewardTime = now
+ }
+ if s.state.Day == s.day() {
+ return nil
+ }
+ s.state.Day = s.day()
+ s.state.SpawnTime = now
+ s.state.Rewarded = map[uint64]bool{}
+ s.state.Regular = nil
+ s.state.Connection = 0
+ s.state.DailyCoins = 0
+ s.state.LastEvent = 0
+ s.state.LastRare = 0
+ owned := slices.Clone(s.owned())
+ slices.Sort(owned)
+ owned = slices.Compact(owned)
+ rand.Shuffle(len(owned), func(i, j int) { owned[i], owned[j] = owned[j], owned[i] })
+ level, _ := s.design.Levels.Row(0, s.state.Level)
+ for _, id := range owned {
+ if r, ok := s.design.Connections.Row(0, id); ok && !s.hasEpisode(r.V(2)) && s.state.Connection == 0 {
+ s.state.Connection = id
+ continue
+ }
+ if _, ok := s.design.Costumes.Row(0, id); ok && uint64(len(s.state.Regular)) < level.V(2) {
+ s.state.Regular = append(s.state.Regular, id)
+ }
+ }
+ return nil
+}
+func (s *Service) canPhone() bool {
+ r, ok := s.design.Connections.Row(0, s.state.Connection)
+ return ok && s.hasEpisode != nil && !s.hasEpisode(r.V(2))
+}
+func (s *Service) CanMeet(ctx command.Context, g uint64) (bool, error) {
+ if e := s.roll(); e != nil {
+ return false, e
+ }
+ r, ok := s.design.Connections.Row(0, s.state.Connection)
+ if !ok || r.V(2) != g || !s.canPhone() {
+ return false, nil
+ }
+ return true, s.save(ctx)
+}
+func (s *Service) infoWire() []byte {
+ b := wire.AppendVarint(nil, 1, s.state.Level)
+ b = wire.AppendVarint(b, 2, uint64(s.state.RewardTime))
+ b = wire.AppendVarint(b, 3, uint64(s.state.SpawnTime))
+ b = wire.AppendVarint(b, 4, s.state.Manage)
+ for _, id := range s.state.Regular {
+ b = wire.AppendVarint(b, 5, id)
+ if s.state.Rewarded[id] {
+ b = wire.AppendVarint(b, 6, id)
+ }
+ }
+ b = wire.AppendVarint(b, 7, s.state.Connection)
+ if s.canPhone() {
+ b = wire.AppendVarint(b, 8, 1)
+ }
+ return wire.AppendVarint(b, 9, s.state.DailyCoins)
+}
+func noteWire(n *note) []byte {
+ b := wire.AppendVarint(nil, 1, n.Costume)
+ b = wire.AppendVarint(b, 2, n.Served)
+ if n.Claimed {
+ b = wire.AppendVarint(b, 3, 1)
+ }
+ return b
+}
+func val(b []byte, n int) uint64 { v, _, _ := wire.Varint(b, n); return v }
+
+var codes = map[string]int{"/CafeteriaInfo": 351, "/CafeteriaSpawnReset": 352, "/CafeteriaLevelUp": 353, "/CafeteriaManageItemAdd": 354, "/CafeteriaRegularCostumeInteractionReward": 355, "/CafeteriaRegularCostumeInteractionAllReward": 356, "/CafeteriaCumulativeReward": 357, "/CafeteriaRegularCostumeNoteInfo": 358, "/CafeteriaRegularCostumeNoteReward": 359, "/CafeteriaRegularCostumeNoteAllReward": 360, "/CafeteriaIntroductionStoryReward": 371, "/CafeteriaDailyConnectionCostumeRefresh": 376, "/CafeteriaRareNpcInteractionReward": 413, "/CafeteriaEventNpcInteractionReward": 414}
+
+func (s *Service) Handle(ctx command.Context, path string, b []byte) (int, []byte, bool, error) {
+ code, ok := codes[path]
+ if !ok {
+ return 0, nil, false, nil
+ }
+ seq := val(b, 1)
+ if seq == 0 || seq > math.MaxInt32 {
+ return code, nil, true, errors.New("cafeteria: missing sequence")
+ }
+ if e := wire.Walk(b, func(wire.Field) error { return nil }); e != nil {
+ return code, nil, true, e
+ }
+ query := path == "/CafeteriaInfo" || path == "/CafeteriaRegularCostumeNoteInfo"
+ rk := fmt.Sprintf("%s:%s:%d", ctx.SessionID, path, seq)
+ digest := sha256.Sum256(append([]byte(path), b...))
+ if !query {
+ if r, ok := s.state.Receipts[rk]; ok {
+ if r.Digest != digest {
+ return code, nil, true, errors.New("cafeteria: changed replay")
+ }
+ return code, slices.Clone(r.Reply), true, nil
+ }
+ }
+ before, _ := json.Marshal(s.state)
+ e := s.roll()
+ var out []byte
+ if e == nil {
+ out, e = s.handle(ctx, path, b, "cafeteria:"+rk)
+ }
+ if e == nil {
+ if !query {
+ s.state.Receipts[rk] = receipt{digest, slices.Clone(out)}
+ }
+ e = s.save(ctx)
+ }
+ if e != nil {
+ _ = json.Unmarshal(before, &s.state)
+ return code, nil, true, e
+ }
+ return code, out, true, nil
+}
+func (s *Service) handle(ctx command.Context, path string, b []byte, identity string) ([]byte, error) {
+ switch path {
+ case "/CafeteriaInfo":
+ out := wire.AppendBytes(nil, 1, s.infoWire())
+ for _, id := range s.state.Facilities {
+ out = wire.AppendBytes(out, 2, wire.AppendVarint(nil, 1, id))
+ }
+ for _, id := range s.state.Managers {
+ out = wire.AppendBytes(out, 3, wire.AppendVarint(nil, 1, id))
+ }
+ return out, nil
+ case "/CafeteriaSpawnReset":
+ out := wire.AppendVarint(nil, 1, s.state.Connection)
+ if s.canPhone() {
+ out = wire.AppendVarint(out, 2, 1)
+ }
+ for _, id := range s.state.Regular {
+ out = wire.AppendVarint(out, 3, id)
+ if s.state.Rewarded[id] {
+ out = wire.AppendVarint(out, 4, id)
+ }
+ }
+ return wire.AppendVarint(out, 5, s.state.DailyCoins), nil
+ case "/CafeteriaDailyConnectionCostumeRefresh":
+ if s.state.Connection == 0 || !s.canPhone() {
+ owned := slices.Clone(s.owned())
+ slices.Sort(owned)
+ for _, id := range owned {
+ r, ok := s.design.Connections.Row(0, id)
+ if ok && !s.hasEpisode(r.V(2)) && !slices.Contains(s.state.Regular, id) {
+ s.state.Connection = id
+ break
+ }
+ }
+ }
+ out := wire.AppendVarint(nil, 1, s.state.Connection)
+ if s.canPhone() {
+ out = wire.AppendVarint(out, 2, 1)
+ }
+ return out, nil
+ case "/CafeteriaIntroductionStoryReward":
+ if s.state.Introduction {
+ return nil, nil
+ }
+ d := s.design.Default
+ bundle, e := s.economy.Apply(ctx, identity, nil, []gamedata.Reward{{Type: d.V(31), ID: d.V(30), Count: d.V(29)}})
+ if e != nil {
+ return nil, e
+ }
+ s.state.Introduction = true
+ return wire.AppendBytes(nil, 1, bundle), nil
+ case "/CafeteriaManageItemAdd":
+ id := s.state.Manage + 1
+ r, ok := s.design.Manage.Row(s.state.Level, id)
+ if !ok {
+ return nil, errors.New("cafeteria: no management upgrade")
+ }
+ var costs []gamedata.Reward
+ if r.V(3) > 0 {
+ costs = append(costs, gamedata.Reward{Type: r.V(2), ID: r.V(1), Count: r.V(3)})
+ }
+ if _, e := s.economy.Apply(ctx, identity, costs, nil); e != nil {
+ return nil, e
+ }
+ s.state.Manage = id
+ out := wire.AppendVarint(nil, 1, id)
+ if f := r.V(4); f > 0 {
+ s.state.Facilities = append(s.state.Facilities, f)
+ out = wire.AppendBytes(out, 2, wire.AppendVarint(nil, 1, f))
+ }
+ if p := r.V(9); p > 0 {
+ s.state.Managers = append(s.state.Managers, p)
+ out = wire.AppendBytes(out, 3, wire.AppendVarint(nil, 1, p))
+ }
+ return out, nil
+ case "/CafeteriaLevelUp":
+ ids := s.design.Manage.Groups[s.state.Level]
+ if len(ids) == 0 || s.state.Manage != ids[len(ids)-1] {
+ return nil, errors.New("cafeteria: management incomplete")
+ }
+ if _, ok := s.design.Levels.Row(0, s.state.Level+1); !ok {
+ return nil, errors.New("cafeteria: maximum level")
+ }
+ bundle, e := s.cumulative(ctx, identity, false)
+ if e != nil {
+ return nil, e
+ }
+ s.state.Level++
+ s.state.Manage = 0
+ out := wire.AppendBytes(nil, 1, s.infoWire())
+ return wire.AppendBytes(out, 2, bundle), nil
+ case "/CafeteriaCumulativeReward":
+ bundle, e := s.cumulative(ctx, identity, true)
+ if e != nil {
+ return nil, e
+ }
+ out := wire.AppendBytes(nil, 1, bundle)
+ return wire.AppendVarint(out, 2, uint64(s.state.RewardTime)), nil
+ case "/CafeteriaRegularCostumeInteractionReward", "/CafeteriaRegularCostumeInteractionAllReward":
+ return s.serve(ctx, b, identity, path == "/CafeteriaRegularCostumeInteractionAllReward")
+ case "/CafeteriaRegularCostumeNoteInfo":
+ var out []byte
+ for _, id := range sortedNotes(s.state.Notes) {
+ out = wire.AppendBytes(out, 1, noteWire(s.state.Notes[id]))
+ }
+ return out, nil
+ case "/CafeteriaRegularCostumeNoteReward", "/CafeteriaRegularCostumeNoteAllReward":
+ return s.claimNotes(ctx, b, identity, path == "/CafeteriaRegularCostumeNoteAllReward")
+ case "/CafeteriaEventNpcInteractionReward":
+ r, ok := s.design.Events.Row(val(b, 2), val(b, 3))
+ if !ok {
+ return nil, errors.New("cafeteria: unknown event")
+ }
+ now := s.now().UnixMilli()
+ if s.state.LastEvent > 0 && now-s.state.LastEvent < int64(s.design.Default.V(3))*1000 {
+ return nil, errors.New("cafeteria: interaction cooldown")
+ }
+ reward := gamedata.Reward{Type: r.V(13), ID: r.V(12), Count: r.V(11)}
+ s.capCoins(&reward)
+ bundle, e := s.grant(ctx, identity, []gamedata.Reward{reward})
+ if e != nil {
+ return nil, e
+ }
+ s.state.LastEvent = now
+ out := wire.AppendBytes(nil, 1, bundle)
+ return wire.AppendVarint(out, 2, s.state.DailyCoins), nil
+ case "/CafeteriaRareNpcInteractionReward":
+ id := val(b, 2)
+ r, ok := s.design.NPCs.Row(0, id)
+ spawn, exists := s.design.UniqueNPCs.Row(0, s.state.Level)
+ if !ok || !exists || !slices.Contains(spawn.A(5), id) {
+ return nil, errors.New("cafeteria: invalid rare NPC")
+ }
+ now := s.now().UnixMilli()
+ if s.state.LastRare > 0 && now-s.state.LastRare < int64(spawn.V(4))*1000 {
+ return nil, errors.New("cafeteria: rare NPC cooldown")
+ }
+ reward := gamedata.Reward{Type: r.V(9), ID: r.V(8), Count: r.V(7)}
+ s.capCoins(&reward)
+ bundle, e := s.grant(ctx, identity, []gamedata.Reward{reward})
+ if e != nil {
+ return nil, e
+ }
+ s.state.LastRare = now
+ return wire.AppendBytes(nil, 1, bundle), nil
+ }
+ return nil, errors.New("cafeteria: unsupported command")
+}
+func (s *Service) grant(ctx command.Context, id string, rewards []gamedata.Reward) ([]byte, error) {
+ filtered := make([]gamedata.Reward, 0, len(rewards))
+ for _, r := range rewards {
+ if r.Count > 0 {
+ filtered = append(filtered, r)
+ }
+ }
+ return s.economy.Apply(ctx, id, nil, filtered)
+}
+func (s *Service) serve(ctx command.Context, b []byte, identity string, all bool) ([]byte, error) {
+ ids := []uint64{val(b, 2)}
+ if all {
+ ids = slices.Clone(s.state.Regular)
+ }
+ var rewards []gamedata.Reward
+ var served []*note
+ for _, id := range ids {
+ if !slices.Contains(s.state.Regular, id) {
+ return nil, errors.New("cafeteria: costume is not today's customer")
+ }
+ if s.state.Rewarded[id] {
+ continue
+ }
+ r, ok := s.design.Costumes.Row(0, id)
+ if !ok {
+ return nil, errors.New("cafeteria: customer missing design")
+ }
+ rewards = append(rewards, gamedata.Reward{Type: r.V(4), ID: r.V(3), Count: r.V(5)})
+ n := s.state.Notes[id]
+ if n == nil {
+ n = ¬e{Costume: id}
+ s.state.Notes[id] = n
+ }
+ n.Served++
+ s.state.Rewarded[id] = true
+ served = append(served, n)
+ }
+ bundle, e := s.grant(ctx, identity, rewards)
+ if e != nil {
+ return nil, e
+ }
+ if !all {
+ out := wire.AppendBytes(nil, 1, bundle)
+ if len(served) > 0 {
+ out = wire.AppendBytes(out, 2, noteWire(served[0]))
+ }
+ return out, nil
+ }
+ out := wire.AppendBytes(nil, 2, bundle)
+ for _, n := range served {
+ out = wire.AppendVarint(out, 1, n.Costume)
+ out = wire.AppendBytes(out, 3, noteWire(n))
+ }
+ return out, nil
+}
+func (s *Service) claimNotes(ctx command.Context, b []byte, identity string, all bool) ([]byte, error) {
+ ids := []uint64{val(b, 2)}
+ if all {
+ ids = sortedNotes(s.state.Notes)
+ }
+ var claimed []uint64
+ var rewards []gamedata.Reward
+ d := s.design.Default
+ for _, id := range ids {
+ n := s.state.Notes[id]
+ if n == nil || n.Served < d.V(7) {
+ if all {
+ continue
+ }
+ return nil, errors.New("cafeteria: note incomplete")
+ }
+ if n.Claimed {
+ continue
+ }
+ claimed = append(claimed, id)
+ rewards = append(rewards, gamedata.Reward{Type: d.V(20), ID: d.V(19), Count: d.V(21)})
+ }
+ bundle, e := s.grant(ctx, identity, rewards)
+ if e != nil {
+ return nil, e
+ }
+ out := wire.AppendBytes(nil, 1, bundle)
+ for _, id := range claimed {
+ s.state.Notes[id].Claimed = true
+ if all {
+ out = wire.AppendVarint(out, 2, id)
+ }
+ }
+ return out, nil
+}
+func (s *Service) capCoins(r *gamedata.Reward) {
+ d := s.design.Default
+ if r.Type == d.V(12) && r.ID == d.V(11) {
+ r.Count = min(r.Count, d.V(8)-min(d.V(8), s.state.DailyCoins))
+ s.state.DailyCoins += r.Count
+ }
+}
+func (s *Service) cumulative(ctx command.Context, identity string, minimum bool) ([]byte, error) {
+ elapsed := max(int64(0), s.now().UnixMilli()-s.state.RewardTime) / 1000
+ d := s.design.Default
+ if minimum && elapsed < int64(d.V(17))*60 {
+ return nil, errors.New("cafeteria: settlement not ready")
+ }
+ elapsed = min(elapsed, int64(d.V(16))*60)
+ r, _ := s.design.Levels.Row(0, s.state.Level)
+ counts, types, terms, ids := r.A(9), r.A(10), r.A(11), r.A(12)
+ if len(counts) != len(types) || len(types) != len(terms) || len(terms) != len(ids) {
+ return nil, errors.New("cafeteria: invalid production design")
+ }
+ var rewards []gamedata.Reward
+ for i, n := range counts {
+ if n > 0 && terms[i] > 0 {
+ count := n * (uint64(elapsed) / terms[i])
+ if count > 0 {
+ rewards = append(rewards, gamedata.Reward{Type: types[i], ID: ids[i], Count: count})
+ }
+ }
+ }
+ bundle, e := s.grant(ctx, identity, rewards)
+ if e != nil {
+ return nil, e
+ }
+ s.state.RewardTime = s.now().UnixMilli()
+ return bundle, nil
+}
+func sortedNotes(m map[uint64]*note) []uint64 {
+ ids := make([]uint64, 0, len(m))
+ for id := range m {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ return ids
+}
diff --git a/go/internal/server/domain/cafeteria/service_test.go b/go/internal/server/domain/cafeteria/service_test.go
new file mode 100644
index 0000000..6cd9d35
--- /dev/null
+++ b/go/internal/server/domain/cafeteria/service_test.go
@@ -0,0 +1,223 @@
+//go:build integration
+
+package cafeteria
+
+import (
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+ "bytes"
+ "fmt"
+ "maps"
+ "testing"
+ "time"
+)
+
+type ledger struct {
+ balances map[[2]uint64]uint64
+}
+
+func (l *ledger) Apply(_ command.Context, _ string, costs, rewards []gamedata.Reward) ([]byte, error) {
+ for _, r := range costs {
+ if l.balances[[2]uint64{r.Type, r.ID}] < r.Count {
+ return nil, fmt.Errorf("insufficient funds")
+ }
+ }
+ for _, r := range costs {
+ l.balances[[2]uint64{r.Type, r.ID}] -= r.Count
+ }
+ for _, r := range rewards {
+ l.balances[[2]uint64{r.Type, r.ID}] += r.Count
+ }
+ return nil, nil
+}
+func liveDesign(t *testing.T) *gamedata.CafeteriaDesign {
+ t.Helper()
+ versions, err := versionconfig.Find()
+ if err != nil {
+ t.Fatal(err)
+ }
+ versionconfig.Use(versions)
+ root, version := versions.Resolve("data/resources/GameData"), versions.GameDataVersion
+ d, e := gamedata.LoadCafeteriaDesign(root, version)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return d
+}
+func TestCafeteriaBusinessSurvivesLoginAndDailyReset(t *testing.T) {
+ d := liveDesign(t)
+ store := stateio.NewMemory()
+ ctx := command.Context{Identity: command.Identity{SessionID: "business"}, State: store}
+ money := &ledger{balances: map[[2]uint64]uint64{}}
+ now := time.Date(2026, 10, 17, 0, 1, 0, 0, time.UTC)
+ costume := d.Costumes.Groups[0][0]
+ open := func() *Service {
+ s, e := Open(ctx, stateio.RootStore{}, d, money)
+ if e != nil {
+ t.Fatal(e)
+ }
+ s.now = func() time.Time { return now }
+ s.AttachOwnedCostumes(func() []uint64 { return []uint64{costume} })
+ s.AttachDatingHasEpisode(func(uint64) bool { return true })
+ return s
+ }
+ s := open()
+ seq := uint64(0)
+ call := func(path string, id uint64) ([]byte, error) {
+ seq++
+ b := wire.AppendVarint(nil, 1, seq)
+ if id > 0 {
+ b = wire.AppendVarint(b, 2, id)
+ }
+ _, out, handled, e := s.Handle(ctx, path, b)
+ if !handled {
+ t.Fatalf("unhandled %s", path)
+ }
+ return out, e
+ }
+ must := func(path string, id uint64) []byte {
+ t.Helper()
+ out, e := call(path, id)
+ if e != nil {
+ t.Fatalf("%s: %v", path, e)
+ }
+ return out
+ }
+ info := must("/CafeteriaInfo", 0)
+ base, _, e := wire.Bytes(info, 1)
+ if e != nil || val(base, 1) == 0 || val(base, 2) == 0 {
+ t.Fatal("client requires initialized business and receipt time")
+ }
+ if _, e = call("/CafeteriaCumulativeReward", 0); e == nil {
+ t.Fatal("settlement before minimum time succeeded")
+ }
+ if _, e = call("/CafeteriaLevelUp", 0); e == nil {
+ t.Fatal("level advanced before management finished")
+ }
+ level := val(base, 1)
+ manage, _ := d.Manage.Row(level, 1)
+ if manage.V(3) > 0 {
+ if _, e = call("/CafeteriaManageItemAdd", 0); e == nil {
+ t.Fatal("unfunded upgrade succeeded")
+ }
+ money.balances[[2]uint64{manage.V(2), manage.V(1)}] = manage.V(3)
+ }
+ must("/CafeteriaManageItemAdd", 0)
+ productionBefore := maps.Clone(money.balances)
+ now = now.Add(time.Duration(d.Default.V(17))*time.Minute + time.Second)
+ must("/CafeteriaCumulativeReward", 0)
+ if maps.Equal(productionBefore, money.balances) {
+ t.Fatal("business generated no production rewards")
+ }
+ for _, manageID := range d.Manage.Groups[level] {
+ if manageID <= 1 {
+ continue
+ }
+ step, _ := d.Manage.Row(level, manageID)
+ currency := [2]uint64{step.V(2), step.V(1)}
+ money.balances[currency] += step.V(3)
+ beforeCost := money.balances[currency]
+ must("/CafeteriaManageItemAdd", 0)
+ if money.balances[currency]+step.V(3) != beforeCost {
+ t.Fatal("management upgrade did not debit its cost")
+ }
+ }
+ upgraded := must("/CafeteriaLevelUp", 0)
+ newBusiness, _, _ := wire.Bytes(upgraded, 1)
+ if val(newBusiness, 1) != level+1 || val(newBusiness, 4) != 0 {
+ t.Fatal("completed management did not advance restaurant level")
+ }
+ before := must("/CafeteriaInfo", 0)
+ s = open()
+ after := must("/CafeteriaInfo", 0)
+ if !bytes.Equal(before, after) {
+ t.Fatal("business state changed across login")
+ }
+ for day := uint64(0); day < d.Default.V(7); day++ {
+ if day > 0 {
+ now = now.Add(24 * time.Hour)
+ must("/CafeteriaSpawnReset", 0)
+ }
+ must("/CafeteriaRegularCostumeInteractionReward", costume)
+ balances := maps.Clone(money.balances)
+ must("/CafeteriaRegularCostumeInteractionReward", costume)
+ if !maps.Equal(money.balances, balances) {
+ t.Fatal("daily interaction was rewarded twice")
+ }
+ notes := must("/CafeteriaRegularCostumeNoteInfo", 0)
+ n, _, _ := wire.Bytes(notes, 1)
+ if val(n, 2) != day+1 {
+ t.Fatal("duplicate daily serve advanced visit progress")
+ }
+ s = open()
+ }
+ balanceKey := [2]uint64{d.Default.V(20), d.Default.V(19)}
+ noteBefore := money.balances[balanceKey]
+ must("/CafeteriaRegularCostumeNoteReward", costume)
+ if money.balances[balanceKey]-noteBefore != d.Default.V(21) {
+ t.Fatal("first note claim did not grant the configured reward")
+ }
+ earned := money.balances[balanceKey]
+ must("/CafeteriaRegularCostumeNoteReward", costume)
+ if money.balances[balanceKey] != earned {
+ t.Fatal("note reward was granted twice")
+ }
+ s = open()
+ n, _, _ := wire.Bytes(must("/CafeteriaRegularCostumeNoteInfo", 0), 1)
+ if val(n, 3) != 1 {
+ t.Fatal("note claim did not survive login")
+ }
+}
+func TestCafeteriaInteractionCapIsSharedAndResets(t *testing.T) {
+ d := liveDesign(t)
+ store := stateio.NewMemory()
+ ctx := command.Context{Identity: command.Identity{SessionID: "cap"}, State: store}
+ money := &ledger{balances: map[[2]uint64]uint64{}}
+ s, e := Open(ctx, stateio.RootStore{}, d, money)
+ if e != nil {
+ t.Fatal(e)
+ }
+ now := time.Date(2026, 10, 17, 0, 1, 0, 0, time.UTC)
+ s.now = func() time.Time { return now }
+ s.AttachOwnedCostumes(func() []uint64 { return nil })
+ s.AttachDatingHasEpisode(func(uint64) bool { return true })
+ var event [2]uint64
+ for k, r := range d.Events.Rows {
+ if r.V(13) == d.Default.V(12) && r.V(12) == d.Default.V(11) && r.V(11) > 0 {
+ event = k
+ break
+ }
+ }
+ seq := uint64(0)
+ call := func() []byte {
+ seq++
+ b := wire.AppendVarint(nil, 1, seq)
+ b = wire.AppendVarint(b, 2, event[0])
+ b = wire.AppendVarint(b, 3, event[1])
+ _, out, _, e := s.Handle(ctx, "/CafeteriaEventNpcInteractionReward", b)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return out
+ }
+ cap := d.Default.V(8)
+ for i := uint64(0); i <= cap; i++ {
+ call()
+ now = now.Add(time.Minute)
+ }
+ currency := [2]uint64{d.Default.V(12), d.Default.V(11)}
+ if money.balances[currency] != cap {
+ t.Fatal("daily interaction rewards exceeded cap")
+ }
+ now = now.Add(72 * time.Hour)
+ out := call()
+ if val(out, 2) == 0 || val(out, 2) > cap {
+ t.Fatal("daily interaction limit did not reset")
+ }
+ if money.balances[currency] > 2*cap {
+ t.Fatal("missed days generated retroactive rewards")
+ }
+}
diff --git a/go/internal/server/domain/command/request_error.go b/go/internal/server/domain/command/request_error.go
new file mode 100644
index 0000000..ace6bb2
--- /dev/null
+++ b/go/internal/server/domain/command/request_error.go
@@ -0,0 +1,16 @@
+package command
+
+import "fmt"
+
+// RequestError identifies the item that failed inside an atomic command.
+type RequestError struct {
+ Path string
+ Sequence uint64
+ Cause error
+}
+
+func (e *RequestError) Error() string {
+ return fmt.Sprintf("%s seq=%d: %v", e.Path, e.Sequence, e.Cause)
+}
+
+func (e *RequestError) Unwrap() error { return e.Cause }
diff --git a/go/internal/server/domain/commerce/gacha/gacha.go b/go/internal/server/domain/commerce/gacha/gacha.go
index 67acd61..0670504 100644
--- a/go/internal/server/domain/commerce/gacha/gacha.go
+++ b/go/internal/server/domain/commerce/gacha/gacha.go
@@ -18,6 +18,7 @@ func (s *Service) infiniteGrant() string {
}
type Service struct {
+ statistics *gamedata.CollectionStatisticsDesign
design *gamedata.InfiniteGachaDesign
first *gamedata.FirstGachaDesign
regular *gamedata.RegularGachaCatalog
diff --git a/go/internal/server/domain/commerce/gacha/history.go b/go/internal/server/domain/commerce/gacha/history.go
new file mode 100644
index 0000000..669b6e2
--- /dev/null
+++ b/go/internal/server/domain/commerce/gacha/history.go
@@ -0,0 +1,257 @@
+package gacha
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+ "fmt"
+ "math"
+)
+
+func (s *Service) AttachStatistics(design *gamedata.CollectionStatisticsDesign) error {
+ if design == nil || len(design.CostumeGrade) == 0 || len(design.Equipment) == 0 {
+ return fmt.Errorf("gacha: incomplete statistics design")
+ }
+ s.statistics = design
+ return nil
+}
+
+func (s *Service) recordHistory(ctx command.Context, identity string, group, id, buyType, count, gachaType, pickup uint64, response []byte, grant roster.CollectionGrant, tickets []byte) error {
+ if group == 0 && s.statistics != nil {
+ group = s.statistics.GachaGroups[id]
+ }
+ if group == 0 {
+ return fmt.Errorf("gacha: draw %d has no history group", id)
+ }
+ var totals [4][13]uint64
+ counts := map[uint64]uint64{}
+ bundle, _, e := wire.Bytes(response, 1)
+ if e != nil {
+ return e
+ }
+ bundle, e = historyRewardBundle(bundle, grant)
+ if e != nil {
+ return e
+ }
+ e = wire.Walk(bundle, func(f wire.Field) error {
+ var itemType, itemID, n uint64
+ switch f.Number {
+ case 3:
+ itemType = 11
+ itemID, _, e = wire.Varint(f.Value, 2)
+ n = 1
+ case 4:
+ itemType = 10
+ var base []byte
+ base, _, e = wire.Bytes(f.Value, 5)
+ if e == nil {
+ itemID, _, e = wire.Varint(base, 1)
+ }
+ n = 1
+ case 9:
+ itemType, _, e = wire.Varint(f.Value, 2)
+ if e == nil {
+ itemID, _, e = wire.Varint(f.Value, 3)
+ }
+ n = 1
+ case 8:
+ itemType, _, e = wire.Varint(f.Value, 1)
+ if e == nil {
+ itemID, _, e = wire.Varint(f.Value, 2)
+ }
+ if e == nil {
+ n, _, e = wire.Varint(f.Value, 3)
+ }
+ default:
+ return nil
+ }
+ if e != nil {
+ return e
+ }
+ if itemType == 11 {
+ counts[itemID] += n
+ return nil
+ }
+ if itemType != 10 {
+ return nil
+ }
+ if s.statistics == nil {
+ return fmt.Errorf("gacha: equipment history needs statistics design")
+ }
+ v, ok := s.statistics.Equipment[itemID]
+ if !ok {
+ return fmt.Errorf("gacha: unknown history equipment %d", itemID)
+ }
+ var grade uint64
+ for _, c := range s.statistics.Characters {
+ if c.UniqueID == v.CharacterUniqueID {
+ grade = c.Grade
+ break
+ }
+ }
+ kind := 3
+ if pickup != 0 {
+ kind = 2
+ }
+ field := -1
+ switch {
+ case grade == 5 && v.Grade == 4:
+ field = 5
+ if itemID == pickup {
+ field = 4
+ }
+ case grade == 5 && v.Grade == 3:
+ field = 6
+ case grade == 4 && v.Grade == 4:
+ field = 7
+ case grade == 4 && v.Grade == 3:
+ field = 8
+ case grade == 4 && v.Grade == 2:
+ field = 9
+ case grade == 3 && v.Grade == 4:
+ field = 10
+ case grade == 3 && v.Grade == 3:
+ field = 11
+ case grade == 3 && v.Grade == 2:
+ field = 12
+ }
+ if field >= 0 {
+ totals[kind][field] += n
+ }
+ return nil
+ })
+ if e != nil {
+ return e
+ }
+ for costume, n := range counts {
+ var grade uint64
+ if s.statistics != nil {
+ grade = s.statistics.CostumeGrade[costume]
+ } else {
+ for _, g := range s.regular.Gachas {
+ if g.Grades[costume] != 0 {
+ grade = g.Grades[costume]
+ break
+ }
+ }
+ }
+ kind := 1
+ if pickup != 0 {
+ kind = 0
+ }
+ switch grade {
+ case 5:
+ field := 1
+ if costume == pickup {
+ field = 0
+ }
+ totals[kind][field] += n
+ case 4:
+ totals[kind][2] += n
+ case 3:
+ totals[kind][3] += n
+ }
+ }
+ body := wire.AppendVarint(nil, 1, group)
+ body = wire.AppendVarint(body, 2, id)
+ body = wire.AppendVarint(body, 3, buyType)
+ body = wire.AppendVarint(body, 4, count)
+ body = wire.AppendVarint(body, 5, grant.GachaPoint)
+ body = wire.AppendVarint(body, 6, gachaType)
+ body = wire.AppendVarint(body, 7, pickup)
+ for _, fixed := range grant.GachaFixed {
+ body = wire.AppendBytes(body, 8, gachaFixedWire(fixed))
+ }
+ body = wire.AppendBytes(body, 9, bundle)
+ for _, index := range grant.CostumeIndices {
+ if c, ok := s.collection.CostumeByIndex(index); ok {
+ body = wire.AppendVarint(body, 10, c.SortID)
+ }
+ }
+ for _, sortID := range grant.SelectionApplySortIDs {
+ body = wire.AppendVarint(body, 11, sortID)
+ }
+ body = append(body, tickets...)
+ now := s.now().UnixMilli()
+ if now <= 0 {
+ return fmt.Errorf("gacha: invalid history time")
+ }
+ return s.collection.RecordGachaHistory(ctx, identity, uint64(now), body, totals)
+}
+
+func historyRewardBundle(raw []byte, grant roster.CollectionGrant) ([]byte, error) {
+ targets := map[[3]uint64]bool{}
+ for _, exchange := range grant.Exchanges {
+ targets[[3]uint64{exchange.ExchangeItemType, exchange.ExchangeItemID, exchange.SortID}] = true
+ }
+ var body []byte
+ err := wire.Walk(raw, func(f wire.Field) error {
+ // History renders original draw results directly, including auto-exchange
+ // origins. Runtime ownership and currency updates would duplicate them.
+ if f.Number == 2 {
+ return nil
+ }
+ if f.Number == 1 {
+ kind, _, e := wire.Varint(f.Value, 3)
+ if e != nil {
+ return e
+ }
+ id, _, e := wire.Varint(f.Value, 2)
+ if e != nil {
+ return e
+ }
+ sort, _, e := wire.Varint(f.Value, 9)
+ if e != nil {
+ return e
+ }
+ if targets[[3]uint64{kind, id, sort}] {
+ return nil
+ }
+ }
+ if f.Type != 2 {
+ return fmt.Errorf("gacha: invalid history reward field")
+ }
+ body = wire.AppendBytes(body, f.Number, f.Value)
+ return nil
+ })
+ return body, err
+}
+
+func historyConsumedTickets(tickets []assets.Item) []byte {
+ var body []byte
+ for _, item := range tickets {
+ v := wire.AppendVarint(nil, 1, item.InvenIndex)
+ v = wire.AppendVarint(v, 2, item.ID)
+ v = wire.AppendVarint(v, 3, item.Type)
+ v = wire.AppendVarint(v, 4, item.Count)
+ body = wire.AppendBytes(body, 12, v)
+ }
+ return body
+}
+
+func (s *Service) gachaHistory(ctx command.Context, raw []byte) (int, []byte, bool, error) {
+ var after uint64
+ seen := false
+ e := wire.Walk(raw, func(f wire.Field) error {
+ if f.Number != 2 {
+ return nil
+ }
+ if f.Type != 0 || seen {
+ return fmt.Errorf("gacha: invalid history cursor")
+ }
+ seen = true
+ var e error
+ after, _, e = wire.Varint(raw, 2)
+ if e != nil || after > math.MaxInt64 {
+ return fmt.Errorf("gacha: invalid history cursor")
+ }
+ return nil
+ })
+ if e != nil {
+ return 201, nil, true, e
+ }
+ body, e := s.collection.GachaHistory(ctx, after)
+ return 201, body, true, e
+}
diff --git a/go/internal/server/domain/commerce/gacha/history_equipment_integration_test.go b/go/internal/server/domain/commerce/gacha/history_equipment_integration_test.go
new file mode 100644
index 0000000..2a9ed5f
--- /dev/null
+++ b/go/internal/server/domain/commerce/gacha/history_equipment_integration_test.go
@@ -0,0 +1,155 @@
+//go:build integration
+
+package gacha
+
+import (
+ "bytes"
+ "testing"
+
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+func TestEquipmentHistoryPreservesScheduledAndTicketDrawReceipts(t *testing.T) {
+ v, e := versionconfig.Find()
+ if e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() {
+ if e := gamedata.CloseDatabaseCache(); e != nil {
+ t.Error(e)
+ }
+ })
+ root := v.Resolve("data/resources/GameData")
+ catalog, e := gamedata.LoadEquipmentGachaGroups(root, v.GameDataVersion, []uint64{5})
+ if e != nil {
+ t.Fatal(e)
+ }
+ design, e := gamedata.LoadCollectionStatistics(root, v.GameDataVersion)
+ if e != nil {
+ t.Fatal(e)
+ }
+ // Independently inspected current GameData: scheduled pickup group 5 and
+ // ticket-only GachaTable 70100001 belonging to static group 1003.
+ group, ok := catalog.Group(5)
+ if !ok {
+ t.Fatal("missing audited pickup group")
+ }
+ ticketDraw, ok := catalog.Gacha(70100001)
+ if !ok || !ticketDraw.TicketOnly || len(ticketDraw.TicketIDs) == 0 {
+ t.Fatal("missing audited exclusive-equipment ticket draw")
+ }
+ ctx := command.Context{Identity: command.Identity{AccountID: "equipment-history", SessionID: "equipment-session"}, State: stateio.NewMemory()}
+ collection, e := roster.OpenCollectionStore(ctx, stateio.RootStore{}, nil)
+ if e != nil {
+ t.Fatal(e)
+ }
+ wallet, e := assets.OpenWallet(ctx, stateio.RootStore{}, assets.Currency{FreeJewelry: 100000})
+ if e != nil {
+ t.Fatal(e)
+ }
+ inventory, e := assets.OpenInventory(ctx, stateio.RootStore{}, nil)
+ if e != nil {
+ t.Fatal(e)
+ }
+ stacks, e := gamedata.LoadItemStackDesign(root, v.GameDataVersion)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = inventory.AttachItemStacks(stacks); e != nil {
+ t.Fatal(e)
+ }
+ tickets, e := inventory.GrantOnce(ctx, "earned-ticket", []gamedata.BattleReward{{ID: ticketDraw.TicketIDs[0], Type: 8, Count: uint64(ticketDraw.Count)}})
+ if e != nil {
+ t.Fatal(e)
+ }
+ if len(tickets) != 1 {
+ t.Fatal("ticket reward not owned")
+ }
+ equipment, e := assets.OpenEquipmentInventory(ctx, stateio.RootStore{})
+ if e != nil {
+ t.Fatal(e)
+ }
+ fixture, _ := selectionService(t)
+ s, e := NewService(nil, fixture.regular, collection, wallet)
+ if e != nil {
+ t.Fatal(e)
+ }
+ s.AttachEquipmentGacha(catalog, equipment)
+ s.AttachInventory(inventory)
+ if e = s.AttachStatistics(design); e != nil {
+ t.Fatal(e)
+ }
+ buy := historyBuy(1, group.OneTimeGachaID)
+ _, response, _, e := s.Handle(ctx, "/GachaBuy", buy)
+ if e != nil {
+ t.Fatal(e)
+ }
+ bundle, _, e := wire.Bytes(response, 1)
+ if e != nil {
+ t.Fatal(e)
+ }
+ awarded := historyFields(t, bundle, 4)
+ if len(awarded) != 1 {
+ t.Fatalf("scheduled single returned %d actual items", len(awarded))
+ }
+ material := wire.AppendVarint(nil, 1, tickets[0].InvenIndex)
+ material = wire.AppendVarint(material, 2, tickets[0].ID)
+ material = wire.AppendVarint(material, 3, tickets[0].Type)
+ material = wire.AppendVarint(material, 4, tickets[0].Count)
+ request := wire.AppendBytes(historyBuy(2, ticketDraw.ID), 4, material)
+ _, ticketResponse, _, e := s.Handle(ctx, "/GachaBuy", request)
+ if e != nil {
+ t.Fatal(e)
+ }
+ ticketBundle, _, e := wire.Bytes(ticketResponse, 1)
+ if e != nil {
+ t.Fatal(e)
+ }
+ collection, e = roster.OpenCollectionStore(ctx, stateio.RootStore{}, nil)
+ if e != nil {
+ t.Fatal(e)
+ }
+ s.collection = collection
+ _, body, _, e := s.Handle(ctx, "/GachaLog", historyQuery(0))
+ if e != nil {
+ t.Fatal(e)
+ }
+ logs := historyFields(t, body, 1)
+ if len(logs) != 2 {
+ t.Fatalf("two completed equipment draws produced %d history records", len(logs))
+ }
+ if historyNumber(t, logs[0], 1) != 1003 || historyNumber(t, logs[0], 2) != ticketDraw.ID || historyNumber(t, logs[0], 6) != 2 {
+ t.Fatalf("ticket result invented a schedule or lost its static group: %x", logs[0])
+ }
+ if historyNumber(t, logs[1], 1) != 5 || historyNumber(t, logs[1], 7) != group.PickUpItemID {
+ t.Fatal("scheduled pickup metadata changed")
+ }
+ for i, expected := range [][]byte{ticketBundle, bundle} {
+ saved, _, err := wire.Bytes(logs[i], 9)
+ if err != nil || !bytes.Equal(saved, expected) {
+ t.Fatal("equipment history replaced or lost the actual awarded equipment")
+ }
+ }
+ materials := historyFields(t, logs[0], 12)
+ if len(materials) != 1 || !bytes.Equal(materials[0], material) {
+ t.Fatal("equipment history lost the actual consumed ticket")
+ }
+ scheduledCosts := historyFields(t, logs[1], 12)
+ scheduledDraw, _ := catalog.Gacha(group.OneTimeGachaID)
+ if len(scheduledCosts) != 1 || historyNumber(t, scheduledCosts[0], 1) != 0 || historyNumber(t, scheduledCosts[0], 2) != 0 || historyNumber(t, scheduledCosts[0], 3) != scheduledDraw.PriceType || historyNumber(t, scheduledCosts[0], 4) != scheduledDraw.Price {
+ t.Fatal("equipment history lost the diamonds actually spent on the scheduled draw")
+ }
+ var total uint64
+ for field := uint64(6); field <= 14; field++ {
+ total += historyTotal(t, body, 2, field) + historyTotal(t, body, 3, field)
+ }
+ if total != 1+uint64(ticketDraw.Count) {
+ t.Fatalf("actual exclusive-equipment reward counts=%d", total)
+ }
+}
diff --git a/go/internal/server/domain/commerce/gacha/history_test.go b/go/internal/server/domain/commerce/gacha/history_test.go
new file mode 100644
index 0000000..4aea711
--- /dev/null
+++ b/go/internal/server/domain/commerce/gacha/history_test.go
@@ -0,0 +1,220 @@
+package gacha
+
+import (
+ "path/filepath"
+ "testing"
+ "time"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+ accountstate "bd2server/internal/server/storage/account"
+ "bd2server/internal/server/storage/stateio"
+)
+
+type historyAccount struct {
+ repo *accountstate.Repository
+ path string
+ catalog *gamedata.RegularGachaCatalog
+ now time.Time
+ name string
+}
+
+func newHistoryAccount(t *testing.T, name string) *historyAccount {
+ t.Helper()
+ catalog, e := gamedata.NewRegularGachaCatalog(map[uint64]gamedata.RegularGacha{
+ 1: {ID: 1, Count: 1, PriceType: 3, Price: 1, Grades: map[uint64]uint64{101: 5}, Pool: []gamedata.WeightedCostume{{ID: 101, Weight: 1}}},
+ 2: {ID: 2, Count: 10, PriceType: 3, Price: 10, Grades: map[uint64]uint64{101: 5}, Pool: []gamedata.WeightedCostume{{ID: 101, Weight: 1}}},
+ 3: {ID: 3, Count: 1, PriceType: 3, Price: 1, Grades: map[uint64]uint64{102: 3}, Pool: []gamedata.WeightedCostume{{ID: 102, Weight: 1}}},
+ }, map[uint64]gamedata.CharacterDesign{101: {ID: 501, HP: 10, CostumeMaxLevel: 5, OverflowItemType: 20, OverflowItemCount: 10}, 102: {ID: 502, HP: 10, CostumeMaxLevel: 5, OverflowItemType: 20, OverflowItemCount: 1}})
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = catalog.AddGroupDesign(gamedata.GachaGroupDesign{ID: 10, GachaType: 1, PickUpCostumeID: 101, PointCount: 1, OneTimeGachaID: 1, TenTimeGachaID: 2}, gamedata.GachaFixedDesign{}); e != nil {
+ t.Fatal(e)
+ }
+ if e = catalog.AddGroupDesign(gamedata.GachaGroupDesign{ID: 20, GachaType: 1, PointCount: 1, OneTimeGachaID: 3}, gamedata.GachaFixedDesign{}); e != nil {
+ t.Fatal(e)
+ }
+ a := &historyAccount{path: filepath.Join(t.TempDir(), "state.db"), catalog: catalog, now: time.Date(2026, 10, 17, 10, 0, 0, 0, time.UTC), name: name}
+ a.repo, e = accountstate.Open(a.path)
+ if e != nil {
+ t.Fatal(e)
+ }
+ t.Cleanup(func() {
+ if e := a.repo.Close(); e != nil {
+ t.Error(e)
+ }
+ })
+ return a
+}
+func (a *historyAccount) reopen(t *testing.T) {
+ t.Helper()
+ if e := a.repo.Close(); e != nil {
+ t.Fatal(e)
+ }
+ var e error
+ a.repo, e = accountstate.Open(a.path)
+ if e != nil {
+ t.Fatal(e)
+ }
+}
+func (a *historyAccount) call(t *testing.T, path string, raw []byte) ([]byte, error) {
+ t.Helper()
+ tx, e := a.repo.BeginCommand(t.Context())
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer func() { _ = tx.Rollback() }()
+ ctx := command.Context{Identity: command.Identity{AccountID: a.name, SessionID: "draw-session"}, State: tx}
+ collection, e := roster.OpenCollectionStore(ctx, stateio.RootStore{}, nil)
+ if e != nil {
+ t.Fatal(e)
+ }
+ wallet, e := assets.OpenWallet(ctx, stateio.RootStore{}, assets.Currency{FreeJewelry: 100000})
+ if e != nil {
+ t.Fatal(e)
+ }
+ s, e := NewService(nil, a.catalog, collection, wallet)
+ if e != nil {
+ t.Fatal(e)
+ }
+ s.now = func() time.Time { return a.now }
+ _, body, handled, e := s.Handle(ctx, path, raw)
+ if !handled {
+ t.Fatalf("unhandled %s", path)
+ }
+ if e != nil {
+ return nil, e
+ }
+ if e = tx.Commit(); e != nil {
+ t.Fatal(e)
+ }
+ return body, nil
+}
+func historyQuery(after uint64) []byte {
+ return wire.AppendVarint(wire.AppendVarint(nil, 1, 999), 2, after)
+}
+func historyBuy(seq, id uint64) []byte {
+ return wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, seq), 2, id), 3, 1)
+}
+func historyFields(t *testing.T, raw []byte, field int) [][]byte {
+ t.Helper()
+ var rows [][]byte
+ if e := wire.Walk(raw, func(f wire.Field) error {
+ if f.Number == field {
+ rows = append(rows, f.Value)
+ }
+ return nil
+ }); e != nil {
+ t.Fatal(e)
+ }
+ return rows
+}
+func historyNumber(t *testing.T, raw []byte, field int) uint64 {
+ t.Helper()
+ n, _, e := wire.Varint(raw, field)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return n
+}
+func historyTotal(t *testing.T, raw []byte, kind, field uint64) uint64 {
+ t.Helper()
+ for _, row := range historyFields(t, raw, 2) {
+ if historyNumber(t, row, 1) == kind {
+ return historyNumber(t, row, int(field))
+ }
+ }
+ t.Fatalf("missing total type %d", kind)
+ return 0
+}
+func (a *historyAccount) must(t *testing.T, path string, raw []byte) []byte {
+ t.Helper()
+ body, e := a.call(t, path, raw)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return body
+}
+
+func TestGachaHistoryUsesCommittedDrawsAndIncrementalCursorAfterReopen(t *testing.T) {
+ a := newHistoryAccount(t, "alice")
+ empty := a.must(t, "/GachaLog", historyQuery(0))
+ if len(historyFields(t, empty, 1)) != 0 {
+ t.Fatal("unplayed account has invented history")
+ }
+ a.must(t, "/GachaBuy", historyBuy(1, 1))
+ first := a.must(t, "/GachaLog", historyQuery(0))
+ rows := historyFields(t, first, 1)
+ if len(rows) != 1 || historyNumber(t, rows[0], 1) != 10 || historyNumber(t, rows[0], 2) != 1 || historyNumber(t, rows[0], 4) != 1 {
+ t.Fatalf("draw metadata not preserved: %x", rows)
+ }
+ cursor := historyNumber(t, rows[0], 13)
+ a.must(t, "/GachaBuy", historyBuy(1, 1))
+ a.reopen(t)
+ a.must(t, "/GachaBuy", historyBuy(1, 1))
+ if got := a.must(t, "/GachaLog", historyQuery(cursor)); len(historyFields(t, got, 1)) != 0 || historyTotal(t, got, 0, 2) != 1 {
+ t.Fatal("retry created another draw or changed lifetime count")
+ }
+ // More than one storage page of genuine single draws share the same clock
+ // millisecond. Every committed receipt must remain reachable from the cursor.
+ for seq := uint64(2); seq <= 270; seq++ {
+ a.must(t, "/GachaBuy", historyBuy(seq, 1))
+ }
+ a.must(t, "/GachaBuy", historyBuy(271, 3))
+ a.must(t, "/GachaBuy", historyBuy(272, 2))
+ a.reopen(t)
+ increment := a.must(t, "/GachaLog", historyQuery(cursor))
+ rows = historyFields(t, increment, 1)
+ if len(rows) != 271 {
+ t.Fatalf("increment lost records across entry pages: %d", len(rows))
+ }
+ previous := uint64(^uint64(0))
+ for _, row := range rows {
+ at := historyNumber(t, row, 13)
+ if at <= cursor || at >= previous {
+ t.Fatal("history cursor order duplicated or skipped a same-millisecond draw")
+ }
+ previous = at
+ }
+ if historyTotal(t, increment, 0, 2) != 280 || historyTotal(t, increment, 1, 5) != 1 {
+ t.Fatalf("costume type totals disagree with 270 singles, ten-pull, and normal three-star draw: %x", historyFields(t, increment, 2))
+ }
+ if all := a.must(t, "/GachaLog", historyQuery(0)); len(historyFields(t, all, 1)) != 272 {
+ t.Fatal("initial query imposed an unsupported history limit")
+ }
+ latest := historyNumber(t, rows[0], 13)
+ a.must(t, "/GachaBuy", historyBuy(273, 1))
+ tail := historyFields(t, a.must(t, "/GachaLog", historyQuery(latest)), 1)
+ if len(tail) != 1 || historyNumber(t, tail[0], 13) <= latest {
+ t.Fatal("new draw at incremental boundary was lost")
+ }
+}
+
+func TestGachaHistoryDoesNotExposeAnotherAccountsDraws(t *testing.T) {
+ alice := newHistoryAccount(t, "alice")
+ bob := newHistoryAccount(t, "bob")
+ alice.must(t, "/GachaBuy", historyBuy(1, 2))
+ bob.reopen(t)
+ if b := bob.must(t, "/GachaLog", historyQuery(0)); len(historyFields(t, b, 1)) != 0 || historyTotal(t, b, 0, 2) != 0 {
+ t.Fatal("another account's history leaked")
+ }
+ bob.must(t, "/GachaBuy", historyBuy(1, 3))
+ bob.reopen(t)
+ b := bob.must(t, "/GachaLog", historyQuery(0))
+ if historyTotal(t, b, 1, 5) != 1 || historyTotal(t, b, 0, 2) != 0 {
+ t.Fatal("account totals were mixed")
+ }
+ if a := alice.must(t, "/GachaLog", historyQuery(0)); historyTotal(t, a, 0, 2) != 10 || historyTotal(t, a, 1, 5) != 0 {
+ t.Fatal("second account changed first account's totals")
+ }
+ if _, e := bob.call(t, "/GachaBuy", historyBuy(2, 999)); e == nil {
+ t.Fatal("unknown draw was accepted")
+ }
+ if b := bob.must(t, "/GachaLog", historyQuery(0)); len(historyFields(t, b, 1)) != 1 {
+ t.Fatal("rejected draw entered history")
+ }
+}
diff --git a/go/internal/server/domain/commerce/gacha/overflow_draw_integration_test.go b/go/internal/server/domain/commerce/gacha/overflow_draw_integration_test.go
new file mode 100644
index 0000000..eb7d870
--- /dev/null
+++ b/go/internal/server/domain/commerce/gacha/overflow_draw_integration_test.go
@@ -0,0 +1,145 @@
+//go:build integration
+
+package gacha
+
+import (
+ "bytes"
+ "testing"
+
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+func TestTwelvePickMaxedDrawHasPlayableResultsAndCreditsOnce(t *testing.T) {
+ v, err := versionconfig.Find()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := gamedata.CloseDatabaseCache(); err != nil {
+ t.Error(err)
+ }
+ })
+ catalog, err := gamedata.LoadRegularCostumeGachaGroups(v.Resolve("data/resources/GameData"), v.GameDataVersion, []uint64{10001}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ group, ok := catalog.Group(10001)
+ if !ok {
+ t.Fatal("12pick unavailable")
+ }
+ var base []roster.Costume
+ seen := map[uint64]bool{}
+ for _, draw := range catalog.Gachas {
+ for id := range draw.Grades {
+ if seen[id] {
+ continue
+ }
+ seen[id] = true
+ design, ok := catalog.Character(id)
+ if !ok {
+ t.Fatal("missing costume design")
+ }
+ base = append(base, roster.Costume{InvenIndex: uint64(len(base) + 1), ID: id, Level: design.CostumeMaxLevel})
+ }
+ }
+ state := stateio.NewMemory()
+ ctx := command.Context{Identity: command.Identity{AccountID: "overflow-player", SessionID: "draw-session"}, State: state}
+ var service *Service
+ open := func() {
+ t.Helper()
+ collection, err := roster.OpenCollectionStore(ctx, stateio.RootStore{}, base)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wallet, err := assets.OpenWallet(ctx, stateio.RootStore{}, assets.Currency{FreeJewelry: 10000})
+ if err != nil {
+ t.Fatal(err)
+ }
+ service, err = NewService(nil, catalog, collection, wallet)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ open()
+ ids := []uint64{806, 101, 102, 103, 104, 105, 106, 201, 202, 203, 204, 301}
+ var choices []roster.GachaSelection
+ for i, id := range ids {
+ choices = append(choices, roster.GachaSelection{GroupID: group.ID, Slot: uint64(i), ItemID: id})
+ }
+ if _, _, _, err := service.Handle(ctx, "/GachaSelectionSave", selectionRequest(choices)); err != nil {
+ t.Fatal(err)
+ }
+ for i, id := range []uint64{group.OneTimeGachaID, group.TenTimeGachaID} {
+ before := service.wallet.Snapshot(ctx)
+ request := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, uint64(i+10)), 2, id), 3, 1)
+ _, body, handled, err := service.Handle(ctx, "/GachaBuy", request)
+ if err != nil || !handled {
+ t.Fatalf("draw: %v", err)
+ }
+ bundle, _, err := wire.Bytes(body, 1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ items := map[uint64][]byte{}
+ exchanges := map[uint64][]byte{}
+ err = wire.Walk(bundle, func(f wire.Field) error {
+ switch f.Number {
+ case 1:
+ sort, _, _ := wire.Varint(f.Value, 9)
+ items[sort] = f.Value
+ case 8:
+ sort, _, _ := wire.Varint(f.Value, 7)
+ exchanges[sort] = f.Value
+ case 2, 3, 9, 10:
+ t.Fatal("maxed draw changed ownership/enhancement or sent duplicate currency credit")
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ draw, _ := catalog.Gacha(id)
+ if len(items) != draw.Count || len(exchanges) != draw.Count {
+ t.Fatal("native result animation cannot restore every draw")
+ }
+ var earned uint64
+ for slot := 0; slot < draw.Count; slot++ {
+ item, exchange := items[uint64(slot)], exchanges[uint64(slot)]
+ costume, _, _ := wire.Varint(exchange, 2)
+ design, ok := catalog.Character(costume)
+ if !ok {
+ t.Fatal("result is not a costume from this banner")
+ }
+ itemType, _, _ := wire.Varint(item, 3)
+ itemID, _, _ := wire.Varint(item, 2)
+ count, _, _ := wire.Varint(item, 4)
+ originalType, _, _ := wire.Varint(exchange, 1)
+ originalCount, _, _ := wire.Varint(exchange, 3)
+ targetType, _, _ := wire.Varint(exchange, 4)
+ targetID, _, _ := wire.Varint(exchange, 5)
+ targetCount, _, _ := wire.Varint(exchange, 6)
+ if originalType != 11 || originalCount != 1 || targetType != itemType || targetID != itemID || targetCount != count {
+ t.Fatal("native exchange cannot restore one costume from its compensation")
+ }
+ if itemType != design.OverflowItemType || itemID != design.OverflowItemID || count != design.OverflowItemCount {
+ t.Fatal("native exchange cannot match the actual compensation by type/id/sort")
+ }
+ earned += count
+ }
+ after := service.wallet.Snapshot(ctx)
+ if after.Mileage != before.Mileage+earned || after.FreeJewelry != before.FreeJewelry-draw.Price {
+ t.Fatal("draw cost or compensation differs from owned assets")
+ }
+ open()
+ _, retry, _, err := service.Handle(ctx, "/GachaBuy", request)
+ if err != nil || !bytes.Equal(body, retry) || service.wallet.Snapshot(ctx) != after {
+ t.Fatal("reopened draw retry changed results or assets")
+ }
+ }
+}
diff --git a/go/internal/server/domain/commerce/gacha/protocol_adapter.go b/go/internal/server/domain/commerce/gacha/protocol_adapter.go
index b25d387..e5bd886 100644
--- a/go/internal/server/domain/commerce/gacha/protocol_adapter.go
+++ b/go/internal/server/domain/commerce/gacha/protocol_adapter.go
@@ -14,7 +14,7 @@ import (
)
func (s *Service) Handle(ctx command.Context, path string, request []byte) (int, []byte, bool, error) {
- if path != "/GachaInfo" && path != "/GachaBuy" && path != "/GachaMultiBuy" && path != "/GachaPointExchange" && path != "/GachaPointManualExchange" && path != "/GachaBuyPreview" && path != "/GachaBuyPreviewLock" && path != "/GachaSelectionSave" && path != "/CashShopPurchaseCountInfo" && path != "/CashShopBuy" {
+ if path != "/GachaLog" && path != "/GachaInfo" && path != "/GachaBuy" && path != "/GachaMultiBuy" && path != "/GachaPointExchange" && path != "/GachaPointManualExchange" && path != "/GachaBuyPreview" && path != "/GachaBuyPreviewLock" && path != "/GachaSelectionSave" && path != "/CashShopPurchaseCountInfo" && path != "/CashShopBuy" {
return 0, nil, false, nil
}
if ctx.SessionID == "" && path != "/GachaInfo" && path != "/CashShopPurchaseCountInfo" {
@@ -25,6 +25,8 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int,
return 0, nil, true, fmt.Errorf("gacha: %s invalid sequence", path)
}
switch path {
+ case "/GachaLog":
+ return s.gachaHistory(ctx, request)
case "/GachaInfo":
return 145, s.gachaInfo(), true, nil
case "/GachaBuyPreview":
@@ -109,9 +111,9 @@ func (s *Service) saveSelection(ctx command.Context, request []byte) (int, []byt
if err != nil {
return err
}
- itemID, itemFound, err := wire.Varint(field.Value, 3)
- if err != nil || !itemFound {
- return errors.New("gacha: selection item missing")
+ itemID, _, err := wire.Varint(field.Value, 3)
+ if err != nil {
+ return err
}
selections = append(selections, roster.GachaSelection{GroupID: groupID, Slot: slot, ItemID: itemID})
return nil
@@ -122,30 +124,27 @@ func (s *Service) saveSelection(ctx command.Context, request []byte) (int, []byt
return 198, nil, true, errors.New("gacha: empty selection")
}
groupID := selections[0].GroupID
- expected := 0
- changeLimit := uint64(0)
- if group, ok := s.regular.Group(groupID); ok && group.SelectCount != 0 {
- expected = int(group.SelectCount)
- changeLimit = group.SelectionChangeCount
+ group, ok := s.regular.Group(groupID)
+ if !ok || group.GachaType != 1 || group.GachaSubType != 1 || group.SelectCount == 0 {
+ return 198, nil, true, fmt.Errorf("gacha: group %d does not support costume selection", groupID)
}
- if expected == 0 || len(selections) != expected {
+ // The client clears an incomplete set with one GroupId-only message.
+ if len(selections) == 1 && selections[0].Slot == 0 && selections[0].ItemID == 0 {
+ if err := s.collection.SaveGachaSelections(ctx, groupID, nil, group.SelectionChangeCount); err != nil {
+ return 198, nil, true, err
+ }
+ return 198, nil, true, nil
+ }
+ expected := int(group.SelectCount)
+ if len(selections) != expected {
return 198, nil, true, fmt.Errorf("gacha: group %d requires %d selections, got %d", groupID, expected, len(selections))
}
- var eligible []uint64
- if s.design != nil {
- eligible = s.design.FiveStarIDs
- }
- if group, ok := s.regular.Group(groupID); ok && group.GachaSubType == 1 && group.TenTimeGachaID != 0 {
- if special := s.regular.SpecialSelectionIDs(group.TenTimeGachaID); len(special) != 0 {
- eligible = special
- } else if fiveStars := s.regular.FiveStarIDs(group.TenTimeGachaID); group.UseSelectionOnlyFixedApply && len(fiveStars) != 0 {
- eligible = fiveStars
+ validItems := make(map[uint64]bool)
+ for _, gachaID := range []uint64{group.OneTimeGachaID, group.TenTimeGachaID} {
+ for _, id := range s.regular.FiveStarIDs(gachaID) {
+ validItems[id] = true
}
}
- validItems := make(map[uint64]bool, len(eligible))
- for _, id := range eligible {
- validItems[id] = true
- }
seenSlots := make(map[uint64]bool, len(selections))
seenItems := make(map[uint64]bool, len(selections))
for _, selection := range selections {
@@ -155,7 +154,7 @@ func (s *Service) saveSelection(ctx command.Context, request []byte) (int, []byt
seenSlots[selection.Slot] = true
seenItems[selection.ItemID] = true
}
- if err := s.collection.SaveGachaSelections(ctx, groupID, selections, changeLimit); err != nil {
+ if err := s.collection.SaveGachaSelections(ctx, groupID, selections, group.SelectionChangeCount); err != nil {
return 198, nil, true, err
}
return 198, nil, true, nil
@@ -413,6 +412,7 @@ func (s *Service) buyWithIdentity(ctx command.Context, request []byte, seq uint6
moonriseSelected[i] = selection.ItemID
}
}
+ var historyCost []byte
stepUpGroupID, stepDesign, isStepUp := s.stepForGacha(id)
if isStepUp && !already {
completed := s.collection.StepUpProgress(stepUpGroupID)
@@ -547,6 +547,14 @@ func (s *Service) buyWithIdentity(ctx command.Context, request []byte, seq uint6
}
}
}
+ historyCost = append(historyConsumedTickets(tickets), historyConsumedTickets(moonriseCost)...)
+ if charge != 0 {
+ kind := uint64(3)
+ if chargePaid {
+ kind = 2
+ }
+ historyCost = append(historyCost, historyConsumedTickets([]assets.Item{{Type: kind, Count: charge}})...)
+ }
purchase := roster.GachaPurchase{Group: group, BuyType: buyType, Fixed: fixedStates, SelectionApplySortIDs: selectionApplySortIDs}
if isMoonrise {
purchase.CompletionGrant = completionGrant
@@ -575,6 +583,11 @@ func (s *Service) buyWithIdentity(ctx command.Context, request []byte, seq uint6
for _, sortID := range grant.SelectionApplySortIDs {
response = wire.AppendVarint(response, 4, sortID)
}
+ if !already {
+ if err := s.recordHistory(ctx, identity, group.ID, id, buyType, uint64(design.Count), group.GachaType, group.PickUpCostumeID, response, grant, historyCost); err != nil {
+ return 146, nil, true, err
+ }
+ }
if !already && s.onDraw != nil {
if err := s.onDraw(ctx, uint64(design.Count)); err != nil {
return 146, nil, true, fmt.Errorf("gacha: draw mission: %w", err)
@@ -625,6 +638,7 @@ func (s *Service) buyEquipmentWithIdentity(ctx command.Context, seq, buyType uin
if identity == "" {
identity = s.requestIdentity(ctx, design.ID, seq)
}
+ historyCost := historyConsumedTickets(tickets)
grant, already := s.collection.Grant(identity)
var entries []assets.Equipment
if already {
@@ -661,6 +675,7 @@ func (s *Service) buyEquipmentWithIdentity(ctx command.Context, seq, buyType uin
if _, err := s.wallet.SpendFreeJewelryOnce(ctx, identity, design.Price/uint64(design.Count)*remain); err != nil {
return 146, nil, true, err
}
+ historyCost = append(historyCost, historyConsumedTickets([]assets.Item{{Type: 3, Count: design.Price / uint64(design.Count) * remain}})...)
}
var fixed gamedata.EquipmentFixedDesign
var priorSR, priorUR uint64
@@ -728,6 +743,11 @@ func (s *Service) buyEquipmentWithIdentity(ctx command.Context, seq, buyType uin
for _, fixed := range grant.GachaFixed {
response = wire.AppendBytes(response, 3, gachaFixedWire(fixed))
}
+ if !already {
+ if err := s.recordHistory(ctx, identity, group.ID, design.ID, buyType, uint64(design.Count), 2, group.PickUpItemID, response, grant, historyCost); err != nil {
+ return 146, nil, true, err
+ }
+ }
if !already && s.onDraw != nil {
if err := s.onDraw(ctx, uint64(design.Count)); err != nil {
return 146, nil, true, fmt.Errorf("gacha: equipment draw mission: %w", err)
@@ -991,7 +1011,11 @@ func (s *Service) confirm(ctx command.Context, request []byte) (int, []byte, boo
if err := s.creditOverflow(ctx, s.infiniteGrant(), grant); err != nil {
return 61, nil, true, err
}
- return 61, wire.AppendBytes(nil, 1, s.rewardBundle(grant)), true, nil
+ response := wire.AppendBytes(nil, 1, s.rewardBundle(grant))
+ if err := s.recordHistory(ctx, s.infiniteGrant(), s.design.GroupID, s.design.GachaID, 1, uint64(s.design.Count), 1, 0, response, grant, nil); err != nil {
+ return 61, nil, true, err
+ }
+ return 61, response, true, nil
}
func (s *Service) rewardBundle(grant roster.CollectionGrant) []byte {
@@ -1040,8 +1064,12 @@ func (s *Service) rewardBundle(grant roster.CollectionGrant) []byte {
}
bundle = wire.AppendBytes(bundle, 9, info)
}
- var repaidMileage uint64
for _, exchange := range grant.Exchanges {
+ item := wire.AppendVarint(nil, 2, exchange.ExchangeItemID)
+ item = wire.AppendVarint(item, 3, exchange.ExchangeItemType)
+ item = wire.AppendVarint(item, 4, exchange.ExchangeCount)
+ item = wire.AppendVarint(item, 9, exchange.SortID)
+ bundle = wire.AppendBytes(bundle, 1, item)
info := wire.AppendVarint(nil, 1, exchange.OriginalItemType)
info = wire.AppendVarint(info, 2, exchange.OriginalItemID)
info = wire.AppendVarint(info, 3, exchange.OriginalCount)
@@ -1054,14 +1082,6 @@ func (s *Service) rewardBundle(grant roster.CollectionGrant) []byte {
info = wire.AppendVarint(info, 7, exchange.SortID)
}
bundle = wire.AppendBytes(bundle, 8, info)
- if exchange.ExchangeItemType == 20 {
- repaidMileage += exchange.ExchangeCount
- }
- }
- if repaidMileage != 0 {
- repaid := wire.AppendVarint(nil, 2, 20)
- repaid = wire.AppendVarint(repaid, 3, repaidMileage)
- bundle = wire.AppendBytes(bundle, 10, repaid)
}
return bundle
}
@@ -1281,6 +1301,9 @@ func (s *Service) confirmFirstGacha(ctx command.Context, _ []byte, seq, buyType
bundle = wire.AppendBytes(bundle, 4, assets.EquipmentWire(entry))
}
response := wire.AppendBytes(nil, 1, bundle)
+ if err := s.recordHistory(ctx, identity, s.first.Group.ID, s.first.GachaID, buyType, uint64(s.first.Count), s.first.Group.GachaType, s.first.Group.PickUpCostumeID, response, grant, nil); err != nil {
+ return 146, nil, true, err
+ }
if err := s.collection.RecordGachaBatch(ctx, responseIdentity, firstGachaResponseDigest, response); err != nil {
return 146, nil, true, err
}
diff --git a/go/internal/server/domain/commerce/gacha/selection_integration_test.go b/go/internal/server/domain/commerce/gacha/selection_integration_test.go
new file mode 100644
index 0000000..58a5eab
--- /dev/null
+++ b/go/internal/server/domain/commerce/gacha/selection_integration_test.go
@@ -0,0 +1,50 @@
+//go:build integration
+
+package gacha
+
+import (
+ "slices"
+ "testing"
+
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/roster"
+)
+
+// GameData 20261012190548: group 10001 -> Gacha 100/101 -> RewardGroup
+// 100/101 -> five-star group 70011 contains costume 806. The live rejected
+// request on 2026-10-17 used group=10001, slot=0, item=806.
+func TestCurrentGameDataTwelvePickAcceptsReportedCostume(t *testing.T) {
+ versions, err := versionconfig.Find()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := gamedata.CloseDatabaseCache(); err != nil {
+ t.Error(err)
+ }
+ })
+ catalog, err := gamedata.LoadRegularCostumeGachaGroups(versions.Resolve("data/resources/GameData"), versions.GameDataVersion, []uint64{10001, 1007}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ service, ctx := selectionService(t)
+ service.regular = catalog
+ // Explicit independently queried targets, with the reported rejection first.
+ ids := []uint64{806, 101, 102, 103, 104, 105, 106, 201, 202, 203, 204, 301}
+ var choices []roster.GachaSelection
+ for i, id := range ids {
+ choices = append(choices, roster.GachaSelection{GroupID: 10001, Slot: uint64(i), ItemID: id})
+ }
+ code, _, handled, err := service.Handle(ctx, "/GachaSelectionSave", selectionRequest(choices))
+ if err != nil || !handled || code != 198 {
+ t.Fatalf("current 12PICK selection rejected: code=%d handled=%v error=%v", code, handled, err)
+ }
+ if got := selectionInfo(t, service, ctx); !slices.Equal(got, choices) {
+ t.Fatalf("12PICK response targets=%v, want %v", got, choices)
+ }
+ // Composite reward programs must retain their selectable five-star pool.
+ if got := catalog.FiveStarIDs(30); !slices.Contains(got, 101) {
+ t.Fatalf("special selection reward program lost costume 101: %v", got)
+ }
+}
diff --git a/go/internal/server/domain/commerce/gacha/selection_test.go b/go/internal/server/domain/commerce/gacha/selection_test.go
new file mode 100644
index 0000000..9c4c837
--- /dev/null
+++ b/go/internal/server/domain/commerce/gacha/selection_test.go
@@ -0,0 +1,184 @@
+package gacha
+
+import (
+ "reflect"
+ "slices"
+ "testing"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+func selectionService(t *testing.T) (*Service, command.Context) {
+ t.Helper()
+ characters := map[uint64]gamedata.CharacterDesign{}
+ grades := map[uint64]uint64{700: 4}
+ var pool []gamedata.WeightedCostume
+ for id := uint64(100); id < 112; id++ {
+ characters[id] = gamedata.CharacterDesign{ID: id}
+ grades[id] = 5
+ if id != 100 {
+ pool = append(pool, gamedata.WeightedCostume{ID: id, Weight: 1})
+ }
+ }
+ characters[700] = gamedata.CharacterDesign{ID: 700}
+ pool = append(pool, gamedata.WeightedCostume{ID: 700, Weight: 1})
+ catalog, err := gamedata.NewRegularGachaCatalog(map[uint64]gamedata.RegularGacha{
+ 1: {ID: 1, Count: 1, PriceType: 3, Price: 200, Pool: []gamedata.WeightedCostume{{ID: 100, Weight: 1}}, Grades: grades},
+ 2: {ID: 2, Count: 10, PriceType: 3, Price: 2000, Pool: pool, Grades: grades},
+ }, characters)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := catalog.AddGroupDesign(gamedata.GachaGroupDesign{ID: 10, GachaType: 1, GachaSubType: 1, PointCount: 1, OneTimeGachaID: 1, TenTimeGachaID: 2, SelectCount: 12}, gamedata.GachaFixedDesign{}); err != nil {
+ t.Fatal(err)
+ }
+ ctx := command.Context{Identity: command.Identity{SessionID: "selection-test"}, State: stateio.NewMemory()}
+ collection, err := roster.OpenCollectionStore(ctx, stateio.RootStore{}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wallet, err := assets.OpenWallet(ctx, stateio.RootStore{}, assets.Currency{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ service, err := NewService(&gamedata.InfiniteGachaDesign{FiveStarIDs: []uint64{999}}, catalog, collection, wallet)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return service, ctx
+}
+
+func selectionRequest(choices []roster.GachaSelection) []byte {
+ request := wire.AppendVarint(nil, 1, 1)
+ for _, choice := range choices {
+ entry := wire.AppendVarint(nil, 1, choice.GroupID)
+ if choice.Slot != 0 {
+ entry = wire.AppendVarint(entry, 2, choice.Slot)
+ }
+ if choice.ItemID != 0 {
+ entry = wire.AppendVarint(entry, 3, choice.ItemID)
+ }
+ request = wire.AppendBytes(request, 2, entry)
+ }
+ return request
+}
+
+func selectionInfo(t *testing.T, service *Service, ctx command.Context) []roster.GachaSelection {
+ t.Helper()
+ code, body, handled, err := service.Handle(ctx, "/GachaInfo", wire.AppendVarint(nil, 1, 2))
+ if err != nil || !handled || code != 145 {
+ t.Fatalf("GachaInfo: code=%d handled=%v error=%v", code, handled, err)
+ }
+ var choices []roster.GachaSelection
+ if err := wire.Walk(body, func(field wire.Field) error {
+ if field.Number == 5 {
+ group, _, err := wire.Varint(field.Value, 1)
+ if err != nil {
+ return err
+ }
+ slot, _, err := wire.Varint(field.Value, 2)
+ if err != nil {
+ return err
+ }
+ item, _, err := wire.Varint(field.Value, 3)
+ choices = append(choices, roster.GachaSelection{GroupID: group, Slot: slot, ItemID: item})
+ return err
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ return choices
+}
+
+// GachaSelectionUI merges the single/ten reward lists and requires all twelve
+// targets (LocalText 1500076/2638); it sends a GroupId-only row to clear them.
+func TestSelectionUsesOwnBannerPoolAndRestoresAndClearsAfterRestart(t *testing.T) {
+ service, ctx := selectionService(t)
+ var want []roster.GachaSelection
+ for i := range uint64(12) {
+ want = append(want, roster.GachaSelection{GroupID: 10, Slot: i, ItemID: 100 + i})
+ }
+ reordered := append([]roster.GachaSelection(nil), want...)
+ slices.Reverse(reordered)
+ code, body, handled, err := service.Handle(ctx, "/GachaSelectionSave", selectionRequest(reordered))
+ if err != nil || !handled || code != 198 || len(body) != 0 {
+ t.Fatalf("save selection: code=%d handled=%v body=%x error=%v", code, handled, body, err)
+ }
+ reopen := func() {
+ t.Helper()
+ collection, err := roster.OpenCollectionStore(ctx, stateio.RootStore{}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ service.collection = collection
+ }
+ reopen()
+ if got := selectionInfo(t, service, ctx); !reflect.DeepEqual(got, want) {
+ t.Fatalf("restarted banner choices=%v, want %v", got, want)
+ }
+ for _, tc := range []struct {
+ name string
+ mutate func([]roster.GachaSelection) []roster.GachaSelection
+ }{
+ {"another banner pool", func(v []roster.GachaSelection) []roster.GachaSelection { v[0].ItemID = 999; return v }},
+ {"non five star", func(v []roster.GachaSelection) []roster.GachaSelection { v[0].ItemID = 700; return v }},
+ {"duplicate target", func(v []roster.GachaSelection) []roster.GachaSelection { v[0].ItemID = v[1].ItemID; return v }},
+ {"duplicate slot", func(v []roster.GachaSelection) []roster.GachaSelection { v[0].Slot = 1; return v }},
+ {"out of range slot", func(v []roster.GachaSelection) []roster.GachaSelection { v[0].Slot = 12; return v }},
+ {"mixed group", func(v []roster.GachaSelection) []roster.GachaSelection { v[1].GroupID = 20; return v }},
+ {"incomplete set", func(v []roster.GachaSelection) []roster.GachaSelection { return v[:11] }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ bad := tc.mutate(append([]roster.GachaSelection(nil), want...))
+ if _, _, _, err := service.Handle(ctx, "/GachaSelectionSave", selectionRequest(bad)); err == nil {
+ t.Fatal("invalid replacement accepted")
+ }
+ reopen()
+ if got := selectionInfo(t, service, ctx); !reflect.DeepEqual(got, want) {
+ t.Fatalf("rejected request changed saved choices: %v", got)
+ }
+ })
+ }
+ code, _, handled, err = service.Handle(ctx, "/GachaSelectionSave", selectionRequest([]roster.GachaSelection{{GroupID: 10}}))
+ if err != nil || !handled || code != 198 {
+ t.Fatalf("clear selection: code=%d handled=%v error=%v", code, handled, err)
+ }
+ reopen()
+ if got := selectionInfo(t, service, ctx); len(got) != 0 {
+ t.Fatalf("cleared targets restored after restart: %v", got)
+ }
+}
+
+func TestClearingSelectionPreservesExhaustedChangeLimit(t *testing.T) {
+ service, ctx := selectionService(t)
+ if err := service.regular.AddGroupDesign(gamedata.GachaGroupDesign{ID: 20, GachaType: 1, GachaSubType: 1, PointCount: 1, OneTimeGachaID: 1, SelectCount: 1, SelectionChangeCount: 1}, gamedata.GachaFixedDesign{}); err != nil {
+ t.Fatal(err)
+ }
+ selected := selectionRequest([]roster.GachaSelection{{GroupID: 20, ItemID: 100}})
+ if _, _, _, err := service.Handle(ctx, "/GachaSelectionSave", selected); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, _, err := service.Handle(ctx, "/GachaSelectionSave", selectionRequest([]roster.GachaSelection{{GroupID: 20}})); err != nil {
+ t.Fatal(err)
+ }
+ collection, err := roster.OpenCollectionStore(ctx, stateio.RootStore{}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ service.collection = collection
+ if len(collection.GachaSelections(20)) != 0 {
+ t.Fatal("clear did not persist")
+ }
+ if got := collection.GachaSelectionChangeCounts(); !reflect.DeepEqual(got, []roster.GachaSelectionChangeCount{{GroupID: 20, Count: 1}}) {
+ t.Fatalf("clear changed the spent allowance: %v", got)
+ }
+ if _, _, _, err := service.Handle(ctx, "/GachaSelectionSave", selected); err == nil {
+ t.Fatal("clearing an exhausted selection reset its change allowance")
+ }
+}
diff --git a/go/internal/server/domain/commerce/npcshop/shop.go b/go/internal/server/domain/commerce/npcshop/shop.go
index bb20e7f..bf6b208 100644
--- a/go/internal/server/domain/commerce/npcshop/shop.go
+++ b/go/internal/server/domain/commerce/npcshop/shop.go
@@ -2,6 +2,7 @@
package npcshop
import (
+ "bd2server/internal/common/util"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
assets "bd2server/internal/server/domain/inventory"
@@ -147,24 +148,13 @@ func (s *Service) rate(p gamedata.NPCProduct, shop, tab uint64) uint64 {
return 100 + p.HighPremium
}
seed := s.marketSeed() + shop + tab + p.Reward.Type + p.Reward.ID
- a := seed
- b := seed + 13*90
- c := a ^ b ^ (a << 16) ^ (b << 15)
- b = seed + 9*90
- b ^= b >> 11
- a = c ^ b
- // WELL512's mask is the unsigned 32-bit pattern 0xDA442D24. The
- // decompiler displays its signed int32 spelling, -633066204, inside
- // an ulong cast; sign-extending that spelling changes the RNG result.
- d := a ^ ((a << 5) & uint64(0xda442d24))
- a = seed + 15*90
- value := a ^ c ^ d ^ (a << 2) ^ (c << 18) ^ (b << 28)
+ random := util.NewWell512(seed)
lo := 100 - p.Discount
span := p.Discount + p.Premium
if span == 0 {
span = 1
}
- return lo + value%span
+ return lo + random.Next()%span
}
// The client keeps ShopRandSeed until the next ShopInfo response. Advancing
diff --git a/go/internal/server/domain/dating/service.go b/go/internal/server/domain/dating/service.go
new file mode 100644
index 0000000..2c3dab8
--- /dev/null
+++ b/go/internal/server/domain/dating/service.go
@@ -0,0 +1,369 @@
+package dating
+
+import (
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "slices"
+ "sort"
+ "time"
+)
+
+type Economy interface {
+ Apply(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error)
+ CanApply(command.Context, []gamedata.Reward) error
+}
+type episode struct {
+ Group, Point, Clear, MessageGroup, Message uint64
+ Updated int64
+}
+type choice struct{ Group, ID, Text uint64 }
+type receipt struct {
+ Digest [32]byte
+ Reply []byte
+}
+type snapshot struct {
+ Version string
+ Episodes map[uint64]*episode
+ Choices map[string]choice
+ Rewards map[string]choice
+ Purchases uint64
+ Day string
+ Receipts map[string]receipt
+}
+type Service struct {
+ store stateio.Store
+ design *gamedata.DatingDesign
+ economy Economy
+ state snapshot
+ now func() time.Time
+ resetSeconds int64
+ firstMeeting func(command.Context, uint64) (bool, error)
+}
+
+func Open(ctx command.Context, store stateio.Store, d *gamedata.DatingDesign, e Economy) (*Service, error) {
+ if store == nil || d == nil || e == nil {
+ return nil, errors.New("dating: missing dependency")
+ }
+ s := &Service{store: store, design: d, economy: e, now: time.Now, resetSeconds: 9 * 3600}
+ b, err := store.Load(ctx.State, "dating")
+ if err != nil {
+ return nil, err
+ }
+ s.state = snapshot{Version: versionconfig.State(), Episodes: map[uint64]*episode{}, Choices: map[string]choice{}, Rewards: map[string]choice{}, Receipts: map[string]receipt{}}
+ if b != nil {
+ if err = stateio.RequireExactJSONObject(b, "Version", "Episodes", "Choices", "Rewards", "Purchases", "Day", "Receipts"); err != nil {
+ return nil, err
+ }
+ if err = json.Unmarshal(b, &s.state); err != nil {
+ return nil, err
+ }
+ if s.state.Version != versionconfig.State() || s.state.Episodes == nil || s.state.Choices == nil || s.state.Rewards == nil || s.state.Receipts == nil {
+ return nil, errors.New("dating: invalid state")
+ }
+ for g, p := range s.state.Episodes {
+ if p == nil || p.Group != g {
+ return nil, errors.New("dating: invalid episode")
+ }
+ if _, ok := d.Episodes.Row(g, p.Clear); !ok {
+ return nil, errors.New("dating: unknown episode")
+ }
+ }
+ }
+ return s, nil
+}
+func (s *Service) AttachFirstMeeting(f func(command.Context, uint64) (bool, error)) {
+ s.firstMeeting = f
+}
+func (s *Service) SetResetSeconds(seconds int64) { s.resetSeconds = seconds }
+func (s *Service) HasEpisode(group uint64) bool { return s.state.Episodes[group] != nil }
+func (s *Service) LastClear(group uint64) uint64 {
+ if p := s.state.Episodes[group]; p != nil {
+ return p.Clear
+ }
+ return 0
+}
+func (s *Service) day() string {
+ return s.now().UTC().Add(time.Duration(9*3600-s.resetSeconds) * time.Second).Format("2006-01-02")
+}
+func (s *Service) save(ctx command.Context) error {
+ b, e := json.Marshal(s.state)
+ if e != nil {
+ return e
+ }
+ return s.store.Save(ctx.State, "dating", b)
+}
+func val(b []byte, n int) uint64 { v, _, _ := wire.Varint(b, n); return v }
+func key(g, id uint64) string { return fmt.Sprintf("%d/%d", g, id) }
+func epWire(p *episode) []byte {
+ b := wire.AppendVarint(nil, 1, p.Group)
+ b = wire.AppendVarint(b, 2, p.Point)
+ b = wire.AppendVarint(b, 3, p.Clear)
+ b = wire.AppendVarint(b, 4, p.MessageGroup)
+ b = wire.AppendVarint(b, 5, p.Message)
+ return wire.AppendVarint(b, 6, uint64(p.Updated))
+}
+func choiceWire(p choice) []byte {
+ b := wire.AppendVarint(nil, 1, p.Group)
+ b = wire.AppendVarint(b, 2, p.ID)
+ if p.Text > 0 {
+ b = wire.AppendVarint(b, 3, p.Text)
+ }
+ return b
+}
+
+var codes = map[string]int{"/DatingInfo": 361, "/DatingEpisodeClear": 362, "/DatingMessageUpdate": 363, "/DatingMessageReward": 527, "/DatingApBuy": 633}
+
+func (s *Service) Handle(ctx command.Context, path string, b []byte) (int, []byte, bool, error) {
+ code, ok := codes[path]
+ if !ok {
+ return 0, nil, false, nil
+ }
+ seq := val(b, 1)
+ if seq == 0 || seq > math.MaxInt32 {
+ return code, nil, true, errors.New("dating: missing sequence")
+ }
+ if e := wire.Walk(b, func(wire.Field) error { return nil }); e != nil {
+ return code, nil, true, e
+ }
+ rk := fmt.Sprintf("%s:%s:%d", ctx.SessionID, path, seq)
+ digest := sha256.Sum256(append([]byte(path), b...))
+ if path != "/DatingInfo" {
+ if r, ok := s.state.Receipts[rk]; ok {
+ if r.Digest != digest {
+ return code, nil, true, errors.New("dating: changed replay")
+ }
+ return code, slices.Clone(r.Reply), true, nil
+ }
+ }
+ before, _ := json.Marshal(s.state)
+ if day := s.day(); day != s.state.Day {
+ s.state.Day = day
+ s.state.Purchases = 0
+ }
+ out, e := s.handle(ctx, path, b, "dating:"+rk)
+ if e == nil {
+ if path != "/DatingInfo" {
+ s.state.Receipts[rk] = receipt{digest, slices.Clone(out)}
+ }
+ e = s.save(ctx)
+ }
+ if e != nil {
+ _ = json.Unmarshal(before, &s.state)
+ return code, nil, true, e
+ }
+ return code, out, true, nil
+}
+func (s *Service) handle(ctx command.Context, path string, b []byte, identity string) ([]byte, error) {
+ g, id := val(b, 2), val(b, 3)
+ switch path {
+ case "/DatingInfo":
+ var out []byte
+ groups := make([]uint64, 0, len(s.state.Episodes))
+ for g := range s.state.Episodes {
+ groups = append(groups, g)
+ }
+ slices.Sort(groups)
+ for _, g := range groups {
+ out = wire.AppendBytes(out, 1, epWire(s.state.Episodes[g]))
+ }
+ for _, entry := range []struct {
+ field int
+ values map[string]choice
+ }{{2, s.state.Choices}, {3, s.state.Rewards}} {
+ keys := make([]string, 0, len(entry.values))
+ for k := range entry.values {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ for _, k := range keys {
+ out = wire.AppendBytes(out, entry.field, choiceWire(entry.values[k]))
+ }
+ }
+ return wire.AppendVarint(out, 4, s.state.Purchases), nil
+ case "/DatingEpisodeClear":
+ r, ok := s.design.Episodes.Row(g, id)
+ if !ok {
+ return nil, errors.New("dating: unknown episode")
+ }
+ p := s.state.Episodes[g]
+ if p != nil && id <= p.Clear {
+ return wire.AppendBytes(nil, 2, epWire(p)), nil
+ }
+ if p == nil {
+ if id != 1 || s.firstMeeting == nil {
+ return nil, errors.New("dating: first meeting unavailable")
+ }
+ allowed, e := s.firstMeeting(ctx, g)
+ if e != nil {
+ return nil, e
+ }
+ if !allowed {
+ return nil, errors.New("dating: first meeting not unlocked")
+ }
+ p = &episode{Group: g}
+ } else if id != p.Clear+1 || r.V(2) == 0 || p.MessageGroup != r.V(2) || p.Message != last(s.design.Messages.Groups[r.V(2)]) {
+ return nil, errors.New("dating: pre-message incomplete")
+ }
+ var costs []gamedata.Reward
+ if id > 1 {
+ cost := gamedata.Reward{Type: 41, Count: 1}
+ if e := s.economy.CanApply(ctx, []gamedata.Reward{cost}); e != nil {
+ if s.design.CostumeGroup[g].V(3) == 1 {
+ return nil, e
+ }
+ cost.Type = 42
+ }
+ costs = append(costs, cost)
+ }
+ var rewards []gamedata.Reward
+ if r.V(8) > 0 {
+ rewards = append(rewards, gamedata.Reward{Type: r.V(11), ID: r.V(10), Count: r.V(8)})
+ }
+ bundle, e := s.economy.Apply(ctx, identity, costs, rewards)
+ if e != nil {
+ return nil, e
+ }
+ p.Clear = id
+ p.Point += r.V(9)
+ s.state.Episodes[g] = p
+ out := wire.AppendBytes(nil, 1, bundle)
+ return wire.AppendBytes(out, 2, epWire(p)), nil
+ case "/DatingMessageUpdate":
+ r, ok := s.design.Messages.Row(g, id)
+ owner, owned := s.design.MessageEpisode[g]
+ if !ok || !owned {
+ return nil, errors.New("dating: unknown message")
+ }
+ p := s.state.Episodes[owner[0]]
+ if p == nil {
+ return nil, errors.New("dating: no first meeting")
+ }
+ text := val(b, 4)
+ if r.V(5) == 1 && r.V(9) == 1 {
+ if text == 0 || (text != r.V(3) && text != r.V(4)) {
+ return nil, errors.New("dating: invalid answer")
+ }
+ } else if text != 0 {
+ return nil, errors.New("dating: message has no answer")
+ }
+ if old, exists := s.state.Choices[key(g, id)]; exists {
+ if old.Text != text {
+ return nil, errors.New("dating: answer immutable")
+ }
+ out := wire.AppendBytes(nil, 1, epWire(p))
+ return wire.AppendBytes(out, 2, choiceWire(old)), nil
+ }
+ if p.MessageGroup == g && id <= p.Message {
+ return wire.AppendBytes(nil, 1, epWire(p)), nil
+ }
+ if !s.nextMessage(p, g, id) {
+ return nil, errors.New("dating: message out of sequence")
+ }
+ if prev, exists := s.design.Messages.Row(p.MessageGroup, p.Message); exists && prev.V(5) == 3 {
+ if _, claimed := s.state.Rewards[key(p.MessageGroup, p.Message)]; !claimed {
+ return nil, errors.New("dating: gift pending")
+ }
+ }
+ p.MessageGroup = g
+ p.Message = id
+ p.Updated = s.now().UnixMilli()
+ out := wire.AppendBytes(nil, 1, epWire(p))
+ if text > 0 {
+ c := choice{g, id, text}
+ s.state.Choices[key(g, id)] = c
+ out = wire.AppendBytes(out, 2, choiceWire(c))
+ }
+ return out, nil
+ case "/DatingMessageReward":
+ r, ok := s.design.Messages.Row(g, id)
+ owner, owned := s.design.MessageEpisode[g]
+ if !ok || !owned || r.V(5) != 3 {
+ return nil, errors.New("dating: message is not a gift")
+ }
+ if _, ok := s.state.Rewards[key(g, id)]; ok {
+ return nil, nil
+ }
+ p := s.state.Episodes[owner[0]]
+ if p == nil || owner[1] >= p.Clear && (p.MessageGroup != g || p.Message < id) {
+ return nil, errors.New("dating: gift unread")
+ }
+ types, ids, counts := r.A(8), r.A(7), r.A(6)
+ if len(types) != len(ids) || len(ids) != len(counts) {
+ return nil, errors.New("dating: invalid gift design")
+ }
+ rewards := make([]gamedata.Reward, 0, len(ids))
+ for i := range ids {
+ if counts[i] > 0 {
+ rewards = append(rewards, gamedata.Reward{Type: types[i], ID: ids[i], Count: counts[i]})
+ }
+ }
+ bundle, e := s.economy.Apply(ctx, identity, nil, rewards)
+ if e != nil {
+ return nil, e
+ }
+ s.state.Rewards[key(g, id)] = choice{Group: g, ID: id}
+ return wire.AppendBytes(nil, 1, bundle), nil
+ case "/DatingApBuy":
+ count := g
+ if count == 0 || count > s.design.Default.V(1)-min(s.state.Purchases, s.design.Default.V(1)) {
+ return nil, errors.New("dating: daily purchase limit")
+ }
+ item, ok, e := wire.Bytes(b, 3)
+ if e != nil || !ok {
+ return nil, errors.New("dating: missing payment")
+ }
+ typ, itemID, amount := val(item, 3), val(item, 2), val(item, 4)
+ types, ids, counts := s.design.Default.A(4), s.design.Default.A(3), s.design.Default.A(2)
+ valid := false
+ for i, t := range types {
+ if i < len(ids) && i < len(counts) && typ == t && itemID == ids[i] && amount == counts[i]*count {
+ valid = true
+ }
+ }
+ if !valid {
+ return nil, errors.New("dating: invalid payment")
+ }
+ bundle, e := s.economy.Apply(ctx, identity, []gamedata.Reward{{Type: typ, ID: itemID, Count: amount}}, []gamedata.Reward{{Type: 42, Count: count}})
+ if e != nil {
+ return nil, e
+ }
+ s.state.Purchases += count
+ out := wire.AppendBytes(nil, 1, bundle)
+ return wire.AppendVarint(out, 2, s.state.Purchases), nil
+ }
+ return nil, errors.New("dating: unsupported command")
+}
+func last(v []uint64) uint64 {
+ if len(v) > 0 {
+ return v[len(v)-1]
+ }
+ return 0
+}
+func (s *Service) nextMessage(p *episode, g, id uint64) bool {
+ if p.MessageGroup == g {
+ return id == p.Message+1
+ }
+ if id != 1 {
+ return false
+ }
+ current, _ := s.design.Episodes.Row(p.Group, p.Clear)
+ if p.MessageGroup == 0 {
+ return g == current.V(3)
+ }
+ if p.Message != last(s.design.Messages.Groups[p.MessageGroup]) {
+ return false
+ }
+ if g == current.V(3) && p.MessageGroup == current.V(2) {
+ return true
+ }
+ next, ok := s.design.Episodes.Row(p.Group, p.Clear+1)
+ return ok && g == next.V(2) && p.MessageGroup == current.V(3)
+}
diff --git a/go/internal/server/domain/dating/service_test.go b/go/internal/server/domain/dating/service_test.go
new file mode 100644
index 0000000..22d663e
--- /dev/null
+++ b/go/internal/server/domain/dating/service_test.go
@@ -0,0 +1,328 @@
+//go:build integration
+
+package dating
+
+import (
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+ "bytes"
+ "fmt"
+ "maps"
+ "testing"
+ "time"
+)
+
+type ledger struct{ balances map[[2]uint64]uint64 }
+
+func (l *ledger) CanApply(_ command.Context, costs []gamedata.Reward) error {
+ for _, r := range costs {
+ if l.balances[[2]uint64{r.Type, r.ID}] < r.Count {
+ return fmt.Errorf("insufficient funds")
+ }
+ }
+ return nil
+}
+func (l *ledger) Apply(ctx command.Context, _ string, costs, rewards []gamedata.Reward) ([]byte, error) {
+ if e := l.CanApply(ctx, costs); e != nil {
+ return nil, e
+ }
+ for _, r := range costs {
+ l.balances[[2]uint64{r.Type, r.ID}] -= r.Count
+ }
+ for _, r := range rewards {
+ l.balances[[2]uint64{r.Type, r.ID}] += r.Count
+ }
+ return nil, nil
+}
+func liveDesign(t *testing.T) *gamedata.DatingDesign {
+ t.Helper()
+ versions, err := versionconfig.Find()
+ if err != nil {
+ t.Fatal(err)
+ }
+ versionconfig.Use(versions)
+ root, version := versions.Resolve("data/resources/GameData"), versions.GameDataVersion
+ d, e := gamedata.LoadDatingDesign(root, version)
+ if e != nil {
+ t.Fatal(e)
+ }
+ return d
+}
+func TestDatingFullConversationPurchaseAndReconnect(t *testing.T) {
+ d := liveDesign(t)
+ store := stateio.NewMemory()
+ ctx := command.Context{Identity: command.Identity{SessionID: "dating"}, State: store}
+ money := &ledger{balances: map[[2]uint64]uint64{{41, 0}: d.Default.V(5)}}
+ now := time.Date(2026, 10, 17, 0, 1, 0, 0, time.UTC)
+ var group uint64
+ for g, c := range d.CostumeGroup {
+ if c.V(3) != 0 {
+ continue
+ }
+ for _, epID := range d.Episodes.Groups[g] {
+ ep, _ := d.Episodes.Row(g, epID)
+ for _, msgID := range d.Messages.Groups[ep.V(3)] {
+ msg, _ := d.Messages.Row(ep.V(3), msgID)
+ if msg.V(5) == 3 {
+ group = g
+ break
+ }
+ }
+ if group != 0 {
+ break
+ }
+ }
+ if group != 0 {
+ break
+ }
+ }
+ if group == 0 {
+ t.Fatal("GameData has no ordinary encounter")
+ }
+ open := func() *Service {
+ s, e := Open(ctx, stateio.RootStore{}, d, money)
+ if e != nil {
+ t.Fatal(e)
+ }
+ s.now = func() time.Time { return now }
+ s.AttachFirstMeeting(func(_ command.Context, g uint64) (bool, error) { return g == group, nil })
+ return s
+ }
+ s := open()
+ seq := uint64(0)
+ call := func(path string, args ...uint64) ([]byte, error) {
+ seq++
+ b := wire.AppendVarint(nil, 1, seq)
+ for i, v := range args {
+ b = wire.AppendVarint(b, i+2, v)
+ }
+ _, out, handled, e := s.Handle(ctx, path, b)
+ if !handled {
+ t.Fatalf("unhandled %s", path)
+ }
+ return out, e
+ }
+ must := func(path string, args ...uint64) []byte {
+ t.Helper()
+ out, e := call(path, args...)
+ if e != nil {
+ t.Fatalf("%s %v: %v", path, args, e)
+ }
+ return out
+ }
+ if _, e := call("/DatingEpisodeClear", group, 2); e == nil {
+ t.Fatal("unmet character bypassed first meeting")
+ }
+ first, _ := d.Episodes.Row(group, 1)
+ firstReward := [2]uint64{first.V(11), first.V(10)}
+ firstBalance := money.balances[firstReward]
+ must("/DatingEpisodeClear", group, 1)
+ if money.balances[firstReward]-firstBalance != first.V(8) {
+ t.Fatal("first meeting reward did not arrive")
+ }
+ if money.balances[[2]uint64{41, 0}] != d.Default.V(5) {
+ t.Fatal("first meeting consumed encounter AP")
+ }
+ balances := maps.Clone(money.balances)
+ must("/DatingEpisodeClear", group, 1)
+ if !maps.Equal(balances, money.balances) {
+ t.Fatal("first meeting rewarded twice")
+ }
+ giftsRead := 0
+ read := func(messageGroup uint64) {
+ t.Helper()
+ for _, id := range d.Messages.Groups[messageGroup] {
+ r, _ := d.Messages.Row(messageGroup, id)
+ text := uint64(0)
+ if r.V(5) == 1 && r.V(9) == 1 {
+ text = r.V(3)
+ }
+ must("/DatingMessageUpdate", messageGroup, id, text)
+ if r.V(5) == 3 {
+ expected := maps.Clone(money.balances)
+ for i, count := range r.A(6) {
+ expected[[2]uint64{r.A(8)[i], r.A(7)[i]}] += count
+ }
+ must("/DatingMessageReward", messageGroup, id)
+ if !maps.Equal(expected, money.balances) {
+ t.Fatal("gift reward did not arrive in the configured quantities")
+ }
+ giftsRead++
+ balances := maps.Clone(money.balances)
+ must("/DatingMessageReward", messageGroup, id)
+ if !maps.Equal(balances, money.balances) {
+ t.Fatal("gift rewarded twice")
+ }
+ }
+ }
+ }
+ read(first.V(3))
+ next, _ := d.Episodes.Row(group, 2)
+ if _, e := call("/DatingEpisodeClear", group, 2); e == nil {
+ t.Fatal("episode cleared without prerequisite conversation")
+ }
+ read(next.V(2))
+ ap := money.balances[[2]uint64{41, 0}]
+ must("/DatingEpisodeClear", group, 2)
+ if money.balances[[2]uint64{41, 0}]+1 != ap {
+ t.Fatal("encounter AP was not consumed")
+ }
+ read(next.V(3))
+ before := must("/DatingInfo")
+ s = open()
+ after := must("/DatingInfo")
+ if !bytes.Equal(before, after) {
+ t.Fatal("dating progress and answers changed across login")
+ }
+ price := d.Default.A(2)[0]
+ typ := d.Default.A(4)[0]
+ id := d.Default.A(3)[0]
+ count := d.Default.V(1)
+ money.balances[[2]uint64{typ, id}] = price * count
+ item := wire.AppendVarint(nil, 2, id)
+ item = wire.AppendVarint(item, 3, typ)
+ item = wire.AppendVarint(item, 4, price*count)
+ seq++
+ b := wire.AppendVarint(nil, 1, seq)
+ b = wire.AppendVarint(b, 2, count)
+ b = wire.AppendBytes(b, 3, item)
+ _, out, _, e := s.Handle(ctx, "/DatingApBuy", b)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if val(out, 2) != count || money.balances[[2]uint64{typ, id}] != 0 || money.balances[[2]uint64{42, 0}] != count {
+ t.Fatal("purchase did not exchange payment for stacked AP")
+ }
+ balances = maps.Clone(money.balances)
+ _, replayed, _, e := s.Handle(ctx, "/DatingApBuy", b)
+ if e != nil || !bytes.Equal(out, replayed) || !maps.Equal(balances, money.balances) {
+ t.Fatal("purchase replay changed balance or reply")
+ }
+ money.balances[[2]uint64{typ, id}] = price
+ balances = maps.Clone(money.balances)
+ seq++
+ excessItem := wire.AppendVarint(nil, 2, id)
+ excessItem = wire.AppendVarint(excessItem, 3, typ)
+ excessItem = wire.AppendVarint(excessItem, 4, price)
+ excess := wire.AppendVarint(nil, 1, seq)
+ excess = wire.AppendVarint(excess, 2, 1)
+ excess = wire.AppendBytes(excess, 3, excessItem)
+ if _, _, _, e = s.Handle(ctx, "/DatingApBuy", excess); e == nil {
+ t.Fatal("daily purchase cap bypassed")
+ }
+ if !maps.Equal(balances, money.balances) || val(must("/DatingInfo"), 4) != count {
+ t.Fatal("rejected over-cap purchase changed balances or purchase count")
+ }
+ s = open()
+ if val(must("/DatingInfo"), 4) != count {
+ t.Fatal("daily purchases lost across login")
+ }
+ now = now.Add(4 * 24 * time.Hour)
+ if val(must("/DatingInfo"), 4) != 0 {
+ t.Fatal("daily purchase limit did not reset")
+ }
+ if money.balances[[2]uint64{42, 0}] != count {
+ t.Fatal("daily reset destroyed stacked AP")
+ }
+ for _, epID := range d.Episodes.Groups[group] {
+ if epID <= 2 {
+ continue
+ }
+ ep, _ := d.Episodes.Row(group, epID)
+ read(ep.V(2))
+ if money.balances[[2]uint64{41, 0}] == 0 && money.balances[[2]uint64{42, 0}] == 0 {
+ now = now.Add(24 * time.Hour)
+ money.balances[[2]uint64{41, 0}] = d.Default.V(5)
+ }
+ prior := maps.Clone(money.balances)
+ currency := uint64(41)
+ if prior[[2]uint64{41, 0}] == 0 {
+ currency = 42
+ }
+ prior[[2]uint64{currency, 0}]--
+ prior[[2]uint64{ep.V(11), ep.V(10)}] += ep.V(8)
+ must("/DatingEpisodeClear", group, epID)
+ if !maps.Equal(prior, money.balances) {
+ t.Fatal("encounter did not consume its AP and grant its episode reward")
+ }
+ read(ep.V(3))
+ }
+ if giftsRead == 0 {
+ t.Fatal("conversation never exercised a gift reward")
+ }
+ before = must("/DatingInfo")
+ s = open()
+ if !bytes.Equal(before, must("/DatingInfo")) {
+ t.Fatal("completed conversation and claimed gift did not survive login")
+ }
+}
+func TestNewRelationshipRejectsPurchasedEncounterAP(t *testing.T) {
+ d := liveDesign(t)
+ var group uint64
+ for g, c := range d.CostumeGroup {
+ if c.V(3) == 1 && len(d.Episodes.Groups[g]) > 1 {
+ group = g
+ break
+ }
+ }
+ if group == 0 {
+ t.Fatal("current GameData has no new relationship")
+ }
+ ctx := command.Context{Identity: command.Identity{SessionID: "new-relation"}, State: stateio.NewMemory()}
+ money := &ledger{balances: map[[2]uint64]uint64{{42, 0}: 10}}
+ s, e := Open(ctx, stateio.RootStore{}, d, money)
+ if e != nil {
+ t.Fatal(e)
+ }
+ s.AttachFirstMeeting(func(_ command.Context, g uint64) (bool, error) { return g == group, nil })
+ seq := uint64(0)
+ call := func(path string, args ...uint64) error {
+ seq++
+ b := wire.AppendVarint(nil, 1, seq)
+ for i, v := range args {
+ b = wire.AppendVarint(b, i+2, v)
+ }
+ _, _, _, e := s.Handle(ctx, path, b)
+ return e
+ }
+ must := func(path string, args ...uint64) {
+ t.Helper()
+ if e := call(path, args...); e != nil {
+ t.Fatalf("%s: %v", path, e)
+ }
+ }
+ must("/DatingEpisodeClear", group, 1)
+ for _, episodeID := range []uint64{1, 2} {
+ r, _ := d.Episodes.Row(group, episodeID)
+ msg := r.V(3)
+ if episodeID == 2 {
+ msg = r.V(2)
+ }
+ for _, id := range d.Messages.Groups[msg] {
+ m, _ := d.Messages.Row(msg, id)
+ text := uint64(0)
+ if m.V(5) == 1 && m.V(9) == 1 {
+ text = m.V(3)
+ }
+ must("/DatingMessageUpdate", msg, id, text)
+ if m.V(5) == 3 {
+ must("/DatingMessageReward", msg, id)
+ }
+ }
+ }
+ before := maps.Clone(money.balances)
+ if e := call("/DatingEpisodeClear", group, 2); e == nil {
+ t.Fatal("purchased AP paid for a new relationship")
+ }
+ if !maps.Equal(before, money.balances) {
+ t.Fatal("rejected encounter changed balances")
+ }
+ money.balances[[2]uint64{41, 0}] = 1
+ must("/DatingEpisodeClear", group, 2)
+ if money.balances[[2]uint64{41, 0}] != 0 || money.balances[[2]uint64{42, 0}] != 10 {
+ t.Fatal("new relationship consumed the wrong AP")
+ }
+}
diff --git a/go/internal/server/domain/events/actions/friendship.go b/go/internal/server/domain/events/actions/friendship.go
new file mode 100644
index 0000000..83b0842
--- /dev/null
+++ b/go/internal/server/domain/events/actions/friendship.go
@@ -0,0 +1,80 @@
+package eventactions
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "fmt"
+ "math"
+ "sort"
+)
+
+func friendshipEpisodeWire(group, id uint64) []byte {
+ return wire.AppendVarint(wire.AppendVarint(nil, 1, group), 2, id)
+}
+
+func (s *Service) friendshipEpisodeInfo() []byte {
+ var completed [][2]uint64
+ for k, claimed := range s.state.Claims {
+ var group, id uint64
+ if claimed {
+ if _, err := fmt.Sscanf(k, "friend:%d/%d", &group, &id); err == nil {
+ completed = append(completed, [2]uint64{group, id})
+ }
+ }
+ }
+ sort.Slice(completed, func(i, j int) bool {
+ if completed[i][0] == completed[j][0] {
+ return completed[i][1] < completed[j][1]
+ }
+ return completed[i][0] < completed[j][0]
+ })
+ var out []byte
+ for _, entry := range completed {
+ out = wire.AppendBytes(out, 1, friendshipEpisodeWire(entry[0], entry[1]))
+ }
+ return out
+}
+
+func (s *Service) clearFriendshipEpisode(ctx command.Context, request []byte, identity string) ([]byte, error) {
+ group, id := val(request, 2), val(request, 3)
+ if group == 0 || id == 0 || group > math.MaxInt32 || id > math.MaxInt32 {
+ return nil, fmt.Errorf("eventactions: invalid friendship episode group=%d episode=%d", group, id)
+ }
+ rule, found := s.row("FriendshipSpecialEpisodeTable", 5, 6, group, id)
+ if !found {
+ return nil, fmt.Errorf("eventactions: unknown friendship episode group=%d episode=%d", group, id)
+ }
+ clearInfo := friendshipEpisodeWire(group, id)
+ claim := "friend:" + key(group, id)
+ if s.state.Claims[claim] {
+ return wire.AppendBytes(nil, 2, clearInfo), nil
+ }
+ seasonal := false
+ for _, schedule := range s.registry.List() {
+ if schedule.Type == 24 && schedule.ID == group && schedule.SubID == id && s.active(schedule) {
+ seasonal = true
+ break
+ }
+ }
+ var level uint64
+ if s.friendship != nil {
+ level = s.friendship(group)
+ }
+ if !seasonal && (level == 0 || level < rule.V(12)) {
+ return nil, fmt.Errorf("eventactions: friendship level insufficient group=%d episode=%d level=%d required=%d", group, id, level, rule.V(12))
+ }
+ if id > 1 && !s.state.Claims["friend:"+key(group, id-1)] {
+ return nil, fmt.Errorf("eventactions: previous friendship episode incomplete group=%d episode=%d previous=%d", group, id, id-1)
+ }
+ rewards := append([]gamedata.Reward(nil), rule.Rewards...)
+ if seasonal {
+ rewards = append(rewards, rule.EventRewards...)
+ }
+ bundle, err := s.economy.Apply(ctx, identity, nil, rewards)
+ if err != nil {
+ return nil, err
+ }
+ s.state.Claims[claim] = true
+ return wire.AppendBytes(wire.AppendBytes(nil, 1, bundle), 2, clearInfo), nil
+}
diff --git a/go/internal/server/domain/events/actions/protocol_adapter.go b/go/internal/server/domain/events/actions/protocol_adapter.go
index e2e902a..f278f16 100644
--- a/go/internal/server/domain/events/actions/protocol_adapter.go
+++ b/go/internal/server/domain/events/actions/protocol_adapter.go
@@ -609,49 +609,9 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st
s.state.Claims[ck] = true
return wire.AppendBytes(nil, 1, bundle), nil
case "/FriendshipSpecialEpisodeInfo":
- var out []byte
- for k := range s.state.Claims {
- var g, id uint64
- if _, e := fmt.Sscanf(k, "friend:%d/%d", &g, &id); e == nil {
- x := wire.AppendVarint(nil, 1, g)
- x = wire.AppendVarint(x, 2, id)
- out = wire.AppendBytes(out, 1, x)
- }
- }
- return out, nil
+ return s.friendshipEpisodeInfo(), nil
case "/FriendshipSpecialEpisodeClear":
- g, id := val(b, 2), val(b, 3)
- r, ok := s.row("FriendshipSpecialEpisodeTable", 5, 6, g, id)
- if !ok {
- return nil, errors.New("eventactions: unknown episode")
- }
- if s.friendship == nil || s.friendship(g) < r.V(12) {
- return nil, errors.New("eventactions: friendship level insufficient")
- }
- if id > 1 && !s.state.Claims["friend:"+key(g, id-1)] {
- return nil, errors.New("eventactions: previous episode incomplete")
- }
- ck := "friend:" + key(g, id)
- if s.state.Claims[ck] {
- return nil, errors.New("eventactions: episode already cleared")
- }
- rs := append([]gamedata.Reward(nil), r.Rewards...)
- for _, v := range s.registry.List() {
- if v.Type == 24 && v.ID == g && s.active(v) {
- rs = append(rs, r.EventRewards...)
- break
- }
- }
- bundle, e := s.economy.Apply(ctx, identity, nil, rs)
- if e != nil {
- return nil, e
- }
- s.state.Claims[ck] = true
- x := wire.AppendVarint(nil, 1, g)
- x = wire.AppendVarint(x, 2, id)
- out := wire.AppendBytes(nil, 1, bundle)
- out = wire.AppendBytes(out, 2, x)
- return out, nil
+ return s.clearFriendshipEpisode(ctx, b, identity)
case "/NpcQuizInfo":
uid := val(b, 2)
v, e := s.resolveQuiz(ctx, uid)
diff --git a/go/internal/server/domain/events/actions/square.go b/go/internal/server/domain/events/actions/square.go
index 2e41521..b8314f7 100644
--- a/go/internal/server/domain/events/actions/square.go
+++ b/go/internal/server/domain/events/actions/square.go
@@ -1,12 +1,11 @@
package eventactions
import (
- "crypto/rand"
+ "bd2server/internal/common/util"
"crypto/sha256"
"encoding/json"
"fmt"
"math"
- "math/big"
"strconv"
"bd2server/internal/server/design/gamedata"
@@ -116,11 +115,7 @@ func squareSample(limit uint64) (uint64, error) {
if limit == 0 {
return 0, fmt.Errorf("eventactions: empty square reward pool")
}
- n, err := rand.Int(rand.Reader, new(big.Int).SetUint64(limit))
- if err != nil {
- return 0, err
- }
- return n.Uint64(), nil
+ return util.RandomUint64N(limit)
}
func (s *Service) square(ctx command.Context, path string, req []byte, identity string) ([]byte, error) {
diff --git a/go/internal/server/domain/events/ap_refresh.go b/go/internal/server/domain/events/ap_refresh.go
index af014b9..911a948 100644
--- a/go/internal/server/domain/events/ap_refresh.go
+++ b/go/internal/server/domain/events/ap_refresh.go
@@ -19,7 +19,7 @@ type economyAPClock struct {
func (e *Economy) AttachAPRefresh(caps map[uint64]uint64, design gamedata.HuntingAPDesign) error {
for typ, max := range caps {
- if (typ != 30 && typ != 32) || max == 0 || max > math.MaxInt32 {
+ if (typ != 30 && typ != 32 && typ != 35) || max == 0 || max > math.MaxInt32 {
return fmt.Errorf("events: invalid free AP refresh")
}
}
@@ -29,6 +29,9 @@ func (e *Economy) AttachAPRefresh(caps map[uint64]uint64, design gamedata.Huntin
return nil
}
func (e *Economy) refreshAP(ctx command.Context, s *economySnapshot) error {
+ if err := e.refreshDatingAP(ctx, s); err != nil {
+ return err
+ }
if len(e.apCaps) == 0 {
return nil
}
@@ -51,7 +54,21 @@ func (e *Economy) refreshAP(ctx command.Context, s *economySnapshot) error {
reset = now >= clock.Next
}
if !reset {
- return nil
+ changed := false
+ for typ, cap := range e.apCaps {
+ if _, found := s.Balances[typ]; !found {
+ s.Balances[typ] = cap
+ changed = true
+ }
+ }
+ if !changed {
+ return nil
+ }
+ raw, err := json.Marshal(s)
+ if err != nil {
+ return err
+ }
+ return e.store.Save(ctx.State, "event_economy", raw)
}
maps.Copy(s.Balances, e.apCaps)
clock.Next = next
@@ -77,7 +94,7 @@ func (e *Economy) CanApply(ctx command.Context, costs []gamedata.Reward) error {
if err = e.refreshAP(ctx, &s); err != nil {
return err
}
- var wallet, ap []gamedata.Reward
+ var wallet, ap, life []gamedata.Reward
var items []assets.Item
totals := map[[2]uint64]uint64{}
for _, r := range costs {
@@ -90,6 +107,8 @@ func (e *Economy) CanApply(ctx command.Context, costs []gamedata.Reward) error {
for k, n := range totals {
r := gamedata.Reward{Type: k[0], ID: k[1], Count: n}
switch {
+ case lifeCurrency(r.Type):
+ life = append(life, r)
case walletCurrency(r.Type):
wallet = append(wallet, r)
case apCurrency(r.Type):
@@ -120,7 +139,15 @@ func (e *Economy) CanApply(ctx command.Context, costs []gamedata.Reward) error {
}
}
if len(items) > 0 {
- return e.items.CanConsume(ctx, items)
+ if err := e.items.CanConsume(ctx, items); err != nil {
+ return err
+ }
+ }
+ if len(life) > 0 {
+ if e.life == nil {
+ return fmt.Errorf("events: life economy unavailable")
+ }
+ return e.life.CanApply(ctx, life, nil)
}
return nil
}
diff --git a/go/internal/server/domain/events/boxes.go b/go/internal/server/domain/events/boxes.go
index 63524f1..3d86c51 100644
--- a/go/internal/server/domain/events/boxes.go
+++ b/go/internal/server/domain/events/boxes.go
@@ -1,16 +1,21 @@
package events
import (
+ "bd2server/internal/server/design/gamedata"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/storage/stateio"
"fmt"
)
type BoxService struct {
- items *assets.Inventory
- economy *Economy
- store stateio.Store
+ resources *gamedata.ResourceItemDesign
+ items *assets.Inventory
+ economy *Economy
+ store stateio.Store
}
+
+func (s *BoxService) AttachResourceItems(design *gamedata.ResourceItemDesign) { s.resources = design }
+
type boxReceipt struct{ Request, Response []byte }
func OpenBoxes(store stateio.Store, items *assets.Inventory, economy *Economy) (*BoxService, error) {
diff --git a/go/internal/server/domain/events/dating_ap.go b/go/internal/server/domain/events/dating_ap.go
new file mode 100644
index 0000000..a7f8323
--- /dev/null
+++ b/go/internal/server/domain/events/dating_ap.go
@@ -0,0 +1,74 @@
+package events
+
+import (
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/storage/stateio"
+ "encoding/json"
+ "fmt"
+ "math"
+ "time"
+)
+
+// AttachDatingAP configures the daily free encounter allowance.
+func (e *Economy) AttachDatingAP(max uint64) error {
+ if max == 0 || max > math.MaxInt32 {
+ return fmt.Errorf("events: invalid dating AP maximum")
+ }
+ e.datingCap = max
+ if e.now == nil {
+ e.now = time.Now
+ }
+ return nil
+}
+func (e *Economy) CurrencyBalance(ctx command.Context, typ uint64) (uint64, error) {
+ if !extraCurrency(typ) {
+ return 0, fmt.Errorf("events: unsupported additional balance")
+ }
+ s, err := e.load(ctx)
+ if err != nil {
+ return 0, err
+ }
+ if err = e.refreshAP(ctx, &s); err != nil {
+ return 0, err
+ }
+ return s.Balances[typ], nil
+}
+
+func (e *Economy) refreshDatingAP(ctx command.Context, s *economySnapshot) error {
+ if e.datingCap == 0 {
+ return nil
+ }
+ now := e.now().UnixMilli()
+ offset := (e.resetSeconds - 9*3600) * 1000
+ next := ((now-offset)/86400000+1)*86400000 + offset
+ raw, err := e.store.Load(ctx.State, "datingapclock")
+ if err != nil {
+ return err
+ }
+ clock := economyAPClock{Next: next}
+ if raw != nil {
+ if err = stateio.RequireExactJSONObject(raw, "next"); err != nil {
+ return err
+ }
+ if err = json.Unmarshal(raw, &clock); err != nil {
+ return err
+ }
+ if now < clock.Next {
+ return nil
+ }
+ }
+ s.Balances[41] = e.datingCap
+ clock.Next = next
+ raw, err = json.Marshal(clock)
+ if err != nil {
+ return err
+ }
+ if err = e.store.Save(ctx.State, "datingapclock", raw); err != nil {
+ return err
+ }
+ raw, err = json.Marshal(s)
+ if err != nil {
+ return err
+ }
+ return e.store.Save(ctx.State, "event_economy", raw)
+}
diff --git a/go/internal/server/domain/events/economy.go b/go/internal/server/domain/events/economy.go
index 2d2d3f1..80a4158 100644
--- a/go/internal/server/domain/events/economy.go
+++ b/go/internal/server/domain/events/economy.go
@@ -36,6 +36,7 @@ type economySnapshot struct {
// Economy dispatches verified static rewards to their owning domains. It is
// called inside the same account transaction as the gameplay operation.
type Economy struct {
+ life LifeEconomy
ownedDesign map[uint64]map[uint64]bool
avatarRewards *gamedata.AvatarRewardDesign
buffRewards *BuffRewards
@@ -51,6 +52,7 @@ type Economy struct {
hunting HuntingAP
prestige map[uint64]uint64
prestigePortrait func() uint64
+ datingCap uint64
apCaps map[uint64]uint64
resetSeconds int64
now func() time.Time
@@ -74,7 +76,7 @@ func NewEconomy(ctx command.Context, store stateio.Store, items *assets.Inventor
// AdditionalCurrencyFields maps EElementType to its UserDBInfo field. These
// balances use a gameplay entry, leaving the frozen wallet schema unchanged.
-var AdditionalCurrencyFields = map[uint64]int{15: 16, 16: 17, 18: 18, 24: 22, 30: 34, 31: 35, 32: 36, 33: 37, 38: 42, 39: 44, 40: 45, 43: 48, 44: 54, 52: 58, 53: 59, 54: 61, 60: 60, 70: 71}
+var AdditionalCurrencyFields = map[uint64]int{15: 16, 16: 17, 18: 18, 24: 22, 30: 34, 31: 35, 32: 36, 33: 37, 35: 41, 38: 42, 39: 44, 40: 45, 41: 46, 42: 47, 43: 48, 44: 54, 52: 58, 53: 59, 54: 61, 60: 60, 70: 71, 72: 70}
func (e *Economy) AttachAvatarRewards(d *gamedata.AvatarRewardDesign) { e.avatarRewards = d }
@@ -96,9 +98,11 @@ func (e *Economy) AdditionalCurrencies(ctx command.Context) (map[int]uint64, err
}
func (e *Economy) load(ctx command.Context) (economySnapshot, error) {
s := economySnapshot{Balances: map[uint64]uint64{}, Receipts: map[string]economyReceipt{}}
- maps.Copy(s.Balances, e.initial)
b, err := e.store.Load(ctx.State, "event_economy")
if err != nil || b == nil {
+ if b == nil {
+ maps.Copy(s.Balances, e.initial)
+ }
return s, err
}
if err = stateio.RequireExactJSONObject(b, "balances", "receipts"); err != nil {
diff --git a/go/internal/server/domain/events/exchange/service.go b/go/internal/server/domain/events/exchange/service.go
index ed15eb7..2dafe7b 100644
--- a/go/internal/server/domain/events/exchange/service.go
+++ b/go/internal/server/domain/events/exchange/service.go
@@ -1,6 +1,7 @@
package eventexchange
import (
+ "bd2server/internal/common/util"
"bd2server/internal/common/versionconfig"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
@@ -8,11 +9,9 @@ import (
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/storage/stateio"
"bytes"
- "crypto/rand"
"encoding/json"
"fmt"
"math"
- "math/big"
"strconv"
"time"
@@ -54,11 +53,7 @@ func Open(ctx command.Context, store stateio.Store, design *gamedata.EventExchan
if n == 0 {
return 0, fmt.Errorf("eventexchange: empty reward pool")
}
- v, e := rand.Int(rand.Reader, new(big.Int).SetUint64(n))
- if e != nil {
- return 0, e
- }
- return v.Uint64(), nil
+ return util.RandomUint64N(n)
}
_, err := s.load(ctx)
return s, err
diff --git a/go/internal/server/domain/events/games/games.go b/go/internal/server/domain/events/games/games.go
index feebac1..b2c949d 100644
--- a/go/internal/server/domain/events/games/games.go
+++ b/go/internal/server/domain/events/games/games.go
@@ -2,15 +2,14 @@
package eventgames
import (
+ "bd2server/internal/common/util"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/events"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/storage/stateio"
- "crypto/rand"
"encoding/json"
"fmt"
- "math/big"
"slices"
"time"
@@ -58,11 +57,7 @@ func Open(ctx command.Context, store stateio.Store, load RuleLoader, resolver Re
if max == 0 {
return 0, fmt.Errorf("eventgames: empty sample")
}
- n, e := rand.Int(rand.Reader, new(big.Int).SetUint64(max))
- if e != nil {
- return 0, e
- }
- return n.Uint64(), nil
+ return util.RandomUint64N(max)
}
raw, e := store.Load(ctx.State, "eventgames")
if e != nil {
diff --git a/go/internal/server/domain/events/life_economy.go b/go/internal/server/domain/events/life_economy.go
new file mode 100644
index 0000000..8c03790
--- /dev/null
+++ b/go/internal/server/domain/events/life_economy.go
@@ -0,0 +1,15 @@
+package events
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+)
+
+type LifeEconomy interface {
+ CanApply(command.Context, []gamedata.Reward, []gamedata.Reward) error
+ Apply(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error)
+}
+
+func (e *Economy) AttachLife(life LifeEconomy) { e.life = life }
+
+func lifeCurrency(typ uint64) bool { return typ >= 64 && typ <= 66 }
diff --git a/go/internal/server/domain/events/play/achievement_progress.go b/go/internal/server/domain/events/play/achievement_progress.go
new file mode 100644
index 0000000..ee98b2f
--- /dev/null
+++ b/go/internal/server/domain/events/play/achievement_progress.go
@@ -0,0 +1,258 @@
+package eventplay
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/events"
+ "bd2server/internal/server/protocol/wire"
+ "fmt"
+ "maps"
+ "slices"
+ "strings"
+)
+
+func (s *Service) CompletedRhythmResults() []events.RhythmResult {
+ if s.completedRhythmResults == nil {
+ s.completedRhythmResults = s.readCompletedRhythmResults()
+ }
+ results := make([]events.RhythmResult, len(s.completedRhythmResults))
+ for i, result := range s.completedRhythmResults {
+ result.Judgments = maps.Clone(result.Judgments)
+ results[i] = result
+ }
+ return results
+}
+
+func (s *Service) readCompletedRhythmResults() []events.RhythmResult {
+ keys := make([]string, 0)
+ for key := range s.state.Replies {
+ if strings.Contains(key, ":/MiniGameRhythmPlayEnd:") {
+ keys = append(keys, key)
+ }
+ }
+ slices.Sort(keys)
+ results := make([]events.RhythmResult, 0, len(keys))
+ for _, key := range keys {
+ reply := s.state.Replies[key]
+ grade := num(reply.Request, 2)
+ if num(reply.Request, 7) != 0 || grade == 0 || grade > 6 {
+ continue
+ }
+ play, found, err := wire.Bytes(reply.Body, 1)
+ if err != nil || !found || num(play, 1) == 0 || num(play, 2) > 2 {
+ continue
+ }
+ result := events.RhythmResult{Music: num(play, 1), Difficulty: num(play, 2), Score: num(reply.Request, 4), Grade: grade, Combo: num(reply.Request, 6), Judgments: map[uint64]uint64{}}
+ if err := wire.Walk(reply.Request, func(field wire.Field) error {
+ if field.Number == 3 {
+ if field.Type != 2 {
+ return wire.ErrMalformed
+ }
+ result.Judgments[num(field.Value, 1)] = num(field.Value, 2)
+ }
+ return nil
+ }); err != nil {
+ continue
+ }
+ results = append(results, result)
+ }
+ return results
+}
+
+func (s *Service) AchievementProgress(design *gamedata.AchievementCounterDesign) (map[[2]uint64]uint64, error) {
+ if design == nil {
+ return nil, fmt.Errorf("eventplay: achievement design unavailable")
+ }
+ if s.achievementProgress != nil && s.achievementDesign == design {
+ return maps.Clone(s.achievementProgress), nil
+ }
+ var stars, survivalBest, defenseBest, rhythmBest, packManBest, packManChain, packManPlays uint64
+ var sichuanBest float64
+ sichuanStages := map[uint64]bool{}
+ rhythmClears := map[uint64]map[uint64]bool{}
+ var hopscotchRecords, hopscotchReplies [3]uint64
+ type actionEvidence struct {
+ records, missions uint64
+ best map[uint64]bool
+ }
+ action := map[[2]uint64]*actionEvidence{}
+ actionScope := func(group, stage uint64) *actionEvidence {
+ key := [2]uint64{group, stage}
+ if action[key] == nil {
+ action[key] = &actionEvidence{best: map[uint64]bool{}}
+ }
+ return action[key]
+ }
+ for _, r := range s.state.Records {
+ switch r.Family {
+ case "Sichuan":
+ if r.Mode == 1 {
+ if r.Clears["clear"] {
+ sichuanStages[r.Stage] = true
+ }
+ for i := range 3 {
+ if r.Clears[fmt.Sprintf("star:%d", i)] {
+ stars++
+ }
+ }
+ } else if r.Mode == 2 && r.BestScore > 0 && (sichuanBest == 0 || r.BestScore < sichuanBest) {
+ sichuanBest = r.BestScore
+ }
+ case "Survival":
+ if r.Stage == 0 {
+ continue
+ }
+ row, err := s.survivalMap(r.Mode, r.Stage)
+ if err != nil {
+ return nil, err
+ }
+ if num(row, 11) == 1 {
+ survivalBest = max(survivalBest, r.Best)
+ }
+ case "Defense":
+ defenseBest = max(defenseBest, r.Best)
+ case "Rhythm":
+ rhythmBest = max(rhythmBest, r.Best)
+ case "Hopscotch":
+ for i, key := range []string{"clear", "full", "no-continue"} {
+ if r.Clears[key] {
+ hopscotchRecords[i]++
+ }
+ }
+ case "PackMan":
+ if r.Mode == 2 {
+ packManBest = max(packManBest, r.Best)
+ }
+ case "Action":
+ if r.Stage > 0 && r.Best > 0 {
+ actionScope(r.Mode, r.Stage).records++
+ }
+ }
+ }
+ for _, result := range s.CompletedRhythmResults() {
+ if rhythmClears[result.Difficulty] == nil {
+ rhythmClears[result.Difficulty] = map[uint64]bool{}
+ }
+ rhythmClears[result.Difficulty][result.Music] = true
+ }
+ seenAction := map[string]bool{}
+ for key, reply := range s.state.Replies {
+ start, end := strings.LastIndex(key, ":/MiniGame"), strings.LastIndexByte(key, ':')
+ if start < 0 || end <= start {
+ continue
+ }
+ switch key[start+1 : end] {
+ case "/MiniGameHopscotchGameEnd":
+ if len(s.design.Tables["HopscotchDefaultTable"]) == 0 {
+ return nil, fmt.Errorf("eventplay: Hopscotch default missing")
+ }
+ area := num(reply.Request, 2)
+ if area < num(s.design.Tables["HopscotchDefaultTable"][0], 4) {
+ continue
+ }
+ hopscotchReplies[0]++
+ if area == 100 {
+ hopscotchReplies[1]++
+ }
+ if num(reply.Request, 4) == 0 {
+ hopscotchReplies[2]++
+ }
+ case "/MiniGamePackManEnd":
+ packManPlays++
+ if num(reply.Request, 5) == 0 {
+ continue
+ }
+ progress, _, err := wire.Bytes(reply.Request, 4)
+ if err != nil {
+ return nil, err
+ }
+ packManChain = max(packManChain, num(progress, 5))
+ case "/MiniGameActionEnd":
+ guid, _, err := wire.Bytes(reply.Request, 2)
+ if err != nil {
+ return nil, err
+ }
+ if len(guid) == 0 || seenAction[string(guid)] {
+ continue
+ }
+ seenAction[string(guid)] = true
+ evidence := actionScope(num(reply.Request, 3), num(reply.Request, 4))
+ if best := num(reply.Body, 1); best > 0 {
+ evidence.best[best] = true
+ }
+ missions, err := list(reply.Body, 2)
+ if err != nil {
+ return nil, err
+ }
+ if len(missions) > 0 {
+ evidence.missions++
+ }
+ }
+ }
+ actionDifficulty, actionMonster := map[uint64]uint64{}, map[uint64]uint64{}
+ for scope, evidence := range action {
+ count := max(evidence.records, evidence.missions, uint64(len(evidence.best)))
+ if count == 0 {
+ continue
+ }
+ for _, stage := range s.design.Rows("ActionGameStageTable", 3, scope[0]) {
+ if num(stage, 4) != scope[1] {
+ continue
+ }
+ monster, err := s.design.Row("ActionGameCharTable", 14, num(stage, 1))
+ if err != nil {
+ return nil, err
+ }
+ actionDifficulty[num(stage, 8)] += count
+ actionMonster[num(monster, 16)] += count
+ break
+ }
+ }
+ allChallengeSongs := len(s.design.Tables["RhythmGameMusicTable"]) > 0
+ for _, music := range s.design.Tables["RhythmGameMusicTable"] {
+ allChallengeSongs = allChallengeSongs && rhythmClears[2][num(music, 5)]
+ }
+ values := map[[2]uint64]uint64{}
+ for _, condition := range design.Conditions {
+ sub := condition.SubType
+ var value uint64
+ switch condition.Type {
+ case 116:
+ value = boolWire(sichuanStages[sub])
+ case 122:
+ value = boolWire(survivalBest > 0 && survivalBest/60 >= sub)
+ case 123:
+ value = boolWire(defenseBest > 0 && defenseBest >= sub)
+ case 124:
+ value = actionDifficulty[sub]
+ case 125:
+ switch sub {
+ case 1:
+ value = boolWire(len(rhythmClears[1]) > 0)
+ case 2:
+ value = boolWire(allChallengeSongs)
+ }
+ case 154:
+ value = stars
+ case 155:
+ value = actionMonster[sub]
+ case 156:
+ value = boolWire(rhythmBest > 0 && rhythmBest >= sub)
+ case 158, 159, 160:
+ index := condition.Type - 158
+ value = max(hopscotchRecords[index], hopscotchReplies[index])
+ case 171:
+ value = packManPlays
+ case 172:
+ value = boolWire(packManChain > 0 && packManChain >= sub)
+ case 173:
+ value = boolWire(packManBest > 0 && packManBest >= sub)
+ case 174:
+ value = boolWire(sichuanBest > 0 && sichuanBest/100 <= float64(sub))
+ default:
+ continue
+ }
+ values[[2]uint64{condition.Type, sub}] = value
+ }
+ s.achievementDesign, s.achievementProgress = design, values
+ return maps.Clone(values), nil
+}
diff --git a/go/internal/server/domain/events/play/achievement_progress_test.go b/go/internal/server/domain/events/play/achievement_progress_test.go
new file mode 100644
index 0000000..e00e3ab
--- /dev/null
+++ b/go/internal/server/domain/events/play/achievement_progress_test.go
@@ -0,0 +1,112 @@
+package eventplay
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/protocol/wire"
+ "reflect"
+ "testing"
+)
+
+func TestRhythmAchievementsRequireCompletedHardAndAllChallengeSongs(t *testing.T) {
+ h := newPlayHarness(t)
+ h.design.Tables["RhythmGameMusicTable"] = [][]byte{
+ testRow(5, 1, 8, 30000, 2, 30000, 1, 30000, 10, 1, 4, 1),
+ testRow(5, 2, 8, 30000, 2, 30000, 1, 30000, 10, 1, 4, 1),
+ }
+ h.design.Tables["RhythmGameCharTable"] = [][]byte{testRow(2, 1)}
+ // GameData 20261012190548 groups 2006/2014 require a HARD clear/all CHALLENGE
+ // songs; groups 2023/2024 require a score of 30000/50000 in any difficulty.
+ design := &gamedata.AchievementCounterDesign{Conditions: map[int]gamedata.AchievementCondition{
+ 2006: {Type: 125, SubType: 1}, 2014: {Type: 125, SubType: 2},
+ 2023: {Type: 156, SubType: 30000}, 2024: {Type: 156, SubType: 50000},
+ }}
+ play := func(seq, music, mode, score uint64, checksum string, gameOver bool) {
+ t.Helper()
+ h.call(t, "/MiniGameRhythmPlayStart", testRow(1, seq, 2, 150, 3, music, 4, 1, 5, mode))
+ grade := uint64(1)
+ if gameOver {
+ grade = 6
+ }
+ end := wire.AppendString(testRow(1, seq+1, 2, grade, 4, score), 5, checksum)
+ if gameOver {
+ end = wire.AppendVarint(end, 7, 1)
+ } else {
+ end = wire.AppendVarint(end, 6, 2)
+ end = wire.AppendBytes(end, 3, testRow(1, 1, 2, 1))
+ }
+ h.call(t, "/MiniGameRhythmPlayEnd", end)
+ }
+ // Four GetRandom(11111, 99999) calls on the official 2.36.7 DLL's Well512
+ // with seeds 30010, 30012, 13, and 30016 supply these independent game IDs.
+ play(1, 1, 1, 30000, "17242-77482-23177-94113", false)
+ play(3, 1, 2, 30000, "60962-43922-45105-49409", false)
+ play(5, 2, 2, 0, "35103-26159-36575-57735", true)
+ h.reopen(t)
+ progress, err := h.service.AchievementProgress(design)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := map[[2]uint64]uint64{{125, 1}: 1, {125, 2}: 0, {156, 30000}: 1, {156, 50000}: 0}
+ if !reflect.DeepEqual(progress, want) {
+ t.Fatalf("quit awarded all-song achievement or completed score was lost: %v", progress)
+ }
+ play(7, 2, 2, 30000, "89338-96162-28825-41345", false)
+ progress, err = h.service.AchievementProgress(design)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want[[2]uint64{125, 2}] = 1
+ if !reflect.DeepEqual(progress, want) {
+ t.Fatalf("all-song challenge achievement stayed stale after settlement: %v", progress)
+ }
+ h.reopen(t)
+ progress, err = h.service.AchievementProgress(design)
+ if err != nil || !reflect.DeepEqual(progress, want) {
+ t.Fatalf("all-song challenge achievement did not survive login: %v, %v", progress, err)
+ }
+}
+
+func TestHopscotchAchievementsCountClearsWithoutCountingPartialRunsOrRetries(t *testing.T) {
+ h := newPlayHarness(t)
+ h.design.Tables["HopscotchDefaultTable"] = [][]byte{testRow(4, 80, 9, 300)}
+ h.design.Tables["HopscotchStageTable"] = [][]byte{testRow(6, 1)}
+ // GameData 20261012190548 groups 2025..2028 count clear/full-completion/
+ // no-continue clears; a partial run after an earlier clear proves no new clear.
+ design := &gamedata.AchievementCounterDesign{Conditions: map[int]gamedata.AchievementCondition{
+ 2025: {Type: 158}, 2026: {Type: 159}, 2027: {Type: 160},
+ }}
+ play := func(seq, area, elapsed, continued uint64) []byte {
+ t.Helper()
+ h.call(t, "/MiniGameHopscotchGameStart", testRow(1, seq, 2, 130, 3, 1))
+ end := testRow(1, seq+1, 2, area, 3, elapsed, 4, continued)
+ h.call(t, "/MiniGameHopscotchGameEnd", end)
+ return end
+ }
+ play(1, 85, 4000, 1)
+ play(3, 100, 5000, 0)
+ partial := play(5, 40, 6000, 0)
+ h.reopen(t)
+ h.call(t, "/MiniGameHopscotchGameEnd", partial)
+ progress, err := h.service.AchievementProgress(design)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := map[[2]uint64]uint64{{158, 0}: 2, {159, 0}: 1, {160, 0}: 1}
+ if !reflect.DeepEqual(progress, want) {
+ t.Fatalf("partial run or retry changed achieved clear counts: %v", progress)
+ }
+ play(7, 80, 4500, 0)
+ progress, err = h.service.AchievementProgress(design)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want[[2]uint64{158, 0}], want[[2]uint64{160, 0}] = 3, 2
+ if !reflect.DeepEqual(progress, want) {
+ t.Fatalf("repeated clear of the same stage was lost: %v", progress)
+ }
+ h.reopen(t)
+ progress, err = h.service.AchievementProgress(design)
+ if err != nil || !reflect.DeepEqual(progress, want) {
+ t.Fatalf("repeated clear progress did not survive login: %v, %v", progress, err)
+ }
+}
diff --git a/go/internal/server/domain/events/play/field_run.go b/go/internal/server/domain/events/play/field_run.go
index 3d507f5..88897d0 100644
--- a/go/internal/server/domain/events/play/field_run.go
+++ b/go/internal/server/domain/events/play/field_run.go
@@ -1,15 +1,14 @@
package eventplay
import (
+ "bd2server/internal/common/util"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/domain/ranking"
"bd2server/internal/server/protocol/wire"
- "crypto/rand"
"encoding/json"
"fmt"
"math"
- "math/big"
"slices"
"strings"
)
@@ -35,11 +34,11 @@ func selectFieldObjects(d *gamedata.EventField) (map[uint64]bool, error) {
}
slices.Sort(ids)
for i := range count {
- n, err := rand.Int(rand.Reader, big.NewInt(int64(len(ids))-int64(i)))
+ n, err := util.RandomUint64N(uint64(len(ids)) - i)
if err != nil {
return nil, err
}
- j := int(i) + int(n.Int64())
+ j := int(i) + int(n)
ids[i], ids[j] = ids[j], ids[i]
selected[ids[i]] = true
}
diff --git a/go/internal/server/domain/events/play/play.go b/go/internal/server/domain/events/play/play.go
index a1e7c31..ea0fd02 100644
--- a/go/internal/server/domain/events/play/play.go
+++ b/go/internal/server/domain/events/play/play.go
@@ -65,6 +65,7 @@ type snapshot struct {
type FieldRuleLoader func(uint64) (*gamedata.EventField, error)
type Service struct {
+ battleCostumes func(command.Context) map[uint64]bool
fieldRules FieldRuleLoader
battleChallenges gamedata.EventBattleChallenges
@@ -79,11 +80,19 @@ type Service struct {
arcadeProfile func(command.Context) (ranking.ArcadeProfile, error)
arcadeGuilds func(command.Context, []uint64) (map[uint64][]byte, error)
onProgress func(command.Context, uint64, uint64, uint64) error
+ onRhythmResult func(command.Context, events.RhythmResult) error
+ achievementDesign *gamedata.AchievementCounterDesign
+ achievementProgress map[[2]uint64]uint64
+ completedRhythmResults []events.RhythmResult
hubCalendars *readonly.Seed
fieldBindings []FieldBinding
actionMissionCharacters map[uint64]uint64
}
+func (s *Service) AttachBattleCostumes(owned func(command.Context) map[uint64]bool) {
+ s.battleCostumes = owned
+}
+
func Open(ctx command.Context, store stateio.Store, design *gamedata.EventPlayCatalog, fieldRules FieldRuleLoader, registry events.Resolver, economy Rewards) (*Service, error) {
if store == nil || design == nil || fieldRules == nil || registry == nil || economy == nil {
return nil, fmt.Errorf("eventplay: incomplete configuration")
diff --git a/go/internal/server/domain/events/play/progress.go b/go/internal/server/domain/events/play/progress.go
index 3dae2b8..e5ddc22 100644
--- a/go/internal/server/domain/events/play/progress.go
+++ b/go/internal/server/domain/events/play/progress.go
@@ -1,7 +1,14 @@
package eventplay
-import "bd2server/internal/server/domain/command"
+import (
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/events"
+)
func (s *Service) AttachProgress(fn func(ctx command.Context, condition, sub, count uint64) error) {
s.onProgress = fn
}
+
+func (s *Service) AttachRhythmResult(fn func(command.Context, events.RhythmResult) error) {
+ s.onRhythmResult = fn
+}
diff --git a/go/internal/server/domain/events/play/protocol_adapter.go b/go/internal/server/domain/events/play/protocol_adapter.go
index d3c3c47..33fee70 100644
--- a/go/internal/server/domain/events/play/protocol_adapter.go
+++ b/go/internal/server/domain/events/play/protocol_adapter.go
@@ -410,6 +410,8 @@ func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []b
var out []byte
var e error
switch path {
+ case "/QuickBattle":
+ out, e = s.quickBattle(ctx, req, key)
case "/MiniGameRelayServerInfo":
provider, ok := s.rooms.(RelayEndpointSource)
if !ok {
@@ -511,6 +513,12 @@ func (s *Service) Handle(ctx command.Context, path string, req []byte) (int, []b
return fail(e)
}
s.state = next
+ if strings.HasSuffix(path, "End") {
+ s.achievementProgress = nil
+ if path == "/MiniGameRhythmPlayEnd" {
+ s.completedRhythmResults = nil
+ }
+ }
return code, out, true, nil
}
@@ -1415,6 +1423,14 @@ func (s *Service) CompleteBattle(ctx command.Context, req []byte, receipt string
next.Stories[marker] = true
}
}
+ hub, e := s.battleHub(ctx, a.UID, false)
+ if e != nil {
+ return nil, e
+ }
+ rs, e = s.battleBonus(ctx, hub, rs)
+ if e != nil {
+ return nil, e
+ }
rewards := []gamedata.Reward{}
for _, r := range rs {
rewards = append(rewards, gamedata.Reward{Type: r.Type, ID: r.ID, Count: r.Count}) //nolint:staticcheck // S1016
diff --git a/go/internal/server/domain/events/play/quick_battle.go b/go/internal/server/domain/events/play/quick_battle.go
new file mode 100644
index 0000000..5362777
--- /dev/null
+++ b/go/internal/server/domain/events/play/quick_battle.go
@@ -0,0 +1,156 @@
+package eventplay
+
+import (
+ "encoding/binary"
+ "fmt"
+ "math"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+)
+
+func (s *Service) quickBattle(ctx command.Context, req []byte, key string) ([]byte, error) {
+ var fields [6]uint64
+ seen := map[int]bool{}
+ if err := wire.Walk(req, func(f wire.Field) error {
+ if f.Number > 6 {
+ return nil
+ }
+ if f.Type != 0 || seen[f.Number] {
+ return fmt.Errorf("eventplay: invalid sweep field")
+ }
+ seen[f.Number] = true
+ fields[f.Number-1], _ = binary.Uvarint(f.Value)
+ if fields[f.Number-1] > math.MaxInt32 {
+ return fmt.Errorf("eventplay: sweep field exceeds int32")
+ }
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ mode, deck, group, stage, count := fields[1], fields[2], fields[3], fields[4], fields[5]
+ if ctx.SessionID == "" || mode != 17 || deck == 0 || group == 0 || stage == 0 || count == 0 || count > 100 {
+ return nil, fmt.Errorf("eventplay: invalid event sweep")
+ }
+ rule, err := s.design.EventBattle(group, stage, deck)
+ if err != nil {
+ return nil, err
+ }
+ if !rule.Quick {
+ return nil, fmt.Errorf("eventplay: sweep disabled for stage")
+ }
+ var uid uint64
+ for _, schedule := range s.registry.List() {
+ if schedule.ID != group || schedule.Type != 8 && schedule.Type != 9 || schedule.UID == 0 || s.now().UnixMilli() < schedule.Start || s.now().UnixMilli() >= schedule.End {
+ continue
+ }
+ if uid != 0 {
+ return nil, fmt.Errorf("eventplay: ambiguous active battle schedule")
+ }
+ uid = schedule.UID
+ }
+ if uid == 0 {
+ return nil, fmt.Errorf("eventplay: event sweep schedule unavailable")
+ }
+ if !s.state.Stories[fmt.Sprintf("battle:%d:%d:%d", uid, group, stage)] {
+ return nil, fmt.Errorf("eventplay: sweep requires completed battle")
+ }
+ if s.battleChallenges == nil {
+ return nil, fmt.Errorf("eventplay: missing battle challenge design")
+ }
+ definitions := s.battleChallenges[deck]
+ for index := range definitions {
+ if !s.state.Stories[fmt.Sprintf("challenge:%d:%d:%d:%d", uid, group, stage, index)] {
+ return nil, fmt.Errorf("eventplay: sweep requires all battle challenges")
+ }
+ }
+ hub, err := s.battleHub(ctx, uid, true)
+ if err != nil {
+ return nil, err
+ }
+ rewards, err := s.battleBonus(ctx, hub, rule.Rewards)
+ if err != nil {
+ return nil, err
+ }
+ var grants []gamedata.Reward
+ for _, r := range rewards {
+ if r.Count > math.MaxInt32/count {
+ return nil, fmt.Errorf("eventplay: sweep reward overflow")
+ }
+ grants = append(grants, gamedata.Reward{Type: r.Type, ID: r.ID, Count: r.Count * count})
+ }
+ var costs []gamedata.Reward
+ if rule.APCost > 0 {
+ if rule.APCost > math.MaxInt32/count {
+ return nil, fmt.Errorf("eventplay: sweep cost overflow")
+ }
+ costs = []gamedata.Reward{{Type: 30, Count: rule.APCost * count}}
+ }
+ bundle, err := s.economy.Apply(ctx, "eventplay:"+key, costs, grants)
+ if err != nil {
+ return nil, err
+ }
+ return wire.AppendBytes(nil, 1, bundle), nil
+}
+
+func (s *Service) battleHub(ctx command.Context, uid uint64, requireOpen bool) (uint64, error) {
+ if s.hubCalendars == nil {
+ return 0, nil
+ }
+ _, body, _, err := s.hubCalendars.Handle(ctx, "/EventHubInfo", wire.AppendVarint(nil, 1, 1))
+ if err != nil {
+ return 0, err
+ }
+ var hub uint64
+ err = wire.Walk(body, func(f wire.Field) error {
+ if f.Number != 1 || f.Type != 2 {
+ return nil
+ }
+ matched := false
+ if err := wire.Walk(f.Value, func(slot wire.Field) error {
+ if slot.Number != 6 || slot.Type != 2 {
+ return nil
+ }
+ uids, err := list(slot.Value, 3)
+ if err != nil {
+ return err
+ }
+ for _, id := range uids {
+ matched = matched || id == uid
+ }
+ return nil
+ }); err != nil {
+ return err
+ }
+ if !matched {
+ return nil
+ }
+ if requireOpen && (s.now().UnixMilli() < int64(num(f.Value, 3)) || s.now().UnixMilli() >= int64(num(f.Value, 4))) {
+ return fmt.Errorf("eventplay: battle hub play window closed")
+ }
+ id := num(f.Value, 2)
+ if id == 0 || hub != 0 && hub != id {
+ return fmt.Errorf("eventplay: ambiguous battle hub")
+ }
+ hub = id
+ return nil
+ })
+ if err != nil {
+ return 0, err
+ }
+ if hub == 0 {
+ return 0, fmt.Errorf("eventplay: battle hub unavailable")
+ }
+ return hub, nil
+}
+
+func (s *Service) battleBonus(ctx command.Context, hub uint64, rewards []gamedata.BattleReward) ([]gamedata.BattleReward, error) {
+ if hub == 0 || len(s.design.Rows("PickUpCostumeEventTable", 3, hub)) == 0 {
+ return rewards, nil
+ }
+ if s.battleCostumes == nil {
+ return nil, fmt.Errorf("eventplay: costume bonus ownership unavailable")
+ }
+ return s.design.EventBattleBonus(hub, s.battleCostumes(ctx), rewards)
+}
diff --git a/go/internal/server/domain/events/play/quick_battle_test.go b/go/internal/server/domain/events/play/quick_battle_test.go
new file mode 100644
index 0000000..23ece85
--- /dev/null
+++ b/go/internal/server/domain/events/play/quick_battle_test.go
@@ -0,0 +1,117 @@
+package eventplay
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/json"
+ "math"
+ "testing"
+ "time"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/events"
+ readonly "bd2server/internal/server/protocol/staticdata"
+ "bd2server/internal/server/protocol/wire"
+)
+
+func setupBattleSweep(t *testing.T) *playHarness {
+ t.Helper()
+ h := newPlayHarness(t)
+ if err := h.registry.Replace([]events.Schedule{{UID: 90, Type: 9, ID: 900, Start: h.now.UnixMilli() - 1000, End: h.now.UnixMilli() + 100000}}); err != nil {
+ t.Fatal(err)
+ }
+ h.design.Tables["PackEventBattleTable"] = [][]byte{testRow(1, 800, 3, 2, 4, 900, 5, 1, 7, 1, 8, 10, 9, 8, 10, 50)}
+ h.design.Tables["PackEventBattleGroupTable"] = [][]byte{testRow(3, 900)}
+ var rate [4]byte
+ binary.LittleEndian.PutUint32(rate[:], math.Float32bits(.5))
+ h.design.Tables["PickUpCostumeEventTable"] = [][]byte{wire.AppendBytes(testRow(2, 777, 3, 3, 4, 1, 5, 50, 6, 8), 1, rate[:])}
+ raw, _ := json.Marshal(map[uint64]uint64{30: 100})
+ if err := h.ctx.State.Save("test-wallet", raw); err != nil {
+ t.Fatal(err)
+ }
+ attachSweepRules(h)
+ return h
+}
+
+func attachSweepRules(h *playHarness) {
+ h.service.AttachBattleChallenges(gamedata.EventBattleChallenges{800: {
+ {Type: 1, Reward: gamedata.BattleReward{Type: 4, Count: 100}},
+ {Type: 2, Reward: gamedata.BattleReward{Type: 4, Count: 20}},
+ }})
+ h.service.AttachBattleCostumes(func(command.Context) map[uint64]bool { return map[uint64]bool{777: true} })
+ h.service.AttachHubCalendars(&readonly.Seed{Responses: map[string]readonly.Response{"/EventHubInfo": {PacketCode: 222, Fields: []readonly.Field{
+ {Number: 1, Type: 2, Fields: []readonly.Field{
+ {Number: 1, Type: 0, Varint: 1000}, {Number: 2, Type: 0, Varint: 3},
+ {Number: 3, Type: 0, Varint: 999999000}, {Number: 4, Type: 0, Varint: 1000100000}, {Number: 5, Type: 0, Varint: 1000200000},
+ {Number: 6, Type: 2, Fields: []readonly.Field{{Number: 1, Type: 0, Varint: 1}, {Number: 2, Type: 0, Varint: 2}, {Number: 3, Type: 0, Varint: 90}}},
+ }},
+ }}}})
+}
+
+func clearSweepBattle(t *testing.T, h *playHarness, receipt string, challenges ...uint64) {
+ t.Helper()
+ if _, err := h.service.EnterBattle(h.ctx, testRow(4, 800, 5, 17, 8, 900, 9, 1), receipt); err != nil {
+ t.Fatal(err)
+ }
+ end := testRow(2, 1)
+ for _, index := range challenges {
+ end = wire.AppendVarint(end, 5, index)
+ }
+ if _, err := h.service.CompleteBattle(h.ctx, end, receipt); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestEventBattleSweepRequiresAllChallengesAndRestoresPaidRewards(t *testing.T) {
+ h := setupBattleSweep(t)
+ req := testRow(1, 5, 2, 17, 3, 800, 4, 900, 5, 1, 6, 3)
+ h.reject(t, "/QuickBattle", req)
+ clearSweepBattle(t, h, "login:1", 0)
+ h.reject(t, "/QuickBattle", req)
+ if h.balance(t, 30) != 98 || h.balance(t, 8) != 15 || h.balance(t, 4) != 100 {
+ t.Fatal("normal clear did not debit AP and grant repeat/first challenge rewards with owned costume bonus")
+ }
+ clearSweepBattle(t, h, "login:2", 1)
+ first := h.call(t, "/QuickBattle", req)
+ if h.balance(t, 30) != 90 || h.balance(t, 8) != 75 || h.balance(t, 4) != 120 {
+ t.Fatal("sweep costs/repeat multiplier or one-time challenge reward is incorrect")
+ }
+ h.reopen(t)
+ attachSweepRules(h)
+ if !bytes.Equal(first, h.call(t, "/QuickBattle", req)) || h.balance(t, 30) != 90 || h.balance(t, 8) != 75 {
+ t.Fatal("reopened sweep retry charged or granted twice")
+ }
+ h.call(t, "/QuickBattle", testRow(1, 6, 2, 17, 3, 800, 4, 900, 5, 1, 6, 1))
+ if h.balance(t, 30) != 88 || h.balance(t, 8) != 90 || h.balance(t, 4) != 120 {
+ t.Fatal("new sweep did not debit and grant exactly one repeat")
+ }
+}
+
+func TestEventBattleSweepRejectsIdentityCostsAndClosedWindowsWithoutAssetChanges(t *testing.T) {
+ h := setupBattleSweep(t)
+ clearSweepBattle(t, h, "login:1", 0, 1)
+ before, _ := h.ctx.State.Load("test-wallet")
+ for _, req := range [][]byte{
+ testRow(1, 2, 2, 17, 3, 801, 4, 900, 5, 1, 6, 1),
+ testRow(1, 2, 2, 17, 3, 800, 4, 900, 5, 2, 6, 1),
+ testRow(1, 2, 2, 17, 3, 800, 4, 901, 5, 1, 6, 1),
+ testRow(1, 2, 2, 1, 3, 800, 4, 900, 5, 1, 6, 1),
+ testRow(1, 2, 2, 17, 3, 800, 4, 900, 5, 1, 6, 0),
+ testRow(1, 2, 2, 17, 3, 800, 4, 900, 5, 1, 6, 101),
+ testRow(1, 2, 2, 17, 3, 800, 4, 900, 5, 1, 6, 50),
+ wire.AppendVarint(testRow(1, 2, 2, 17, 3, 800, 4, 900, 5, 1, 6, 1), 6, 1),
+ } {
+ h.reject(t, "/QuickBattle", req)
+ }
+ row := h.design.Tables["PackEventBattleTable"][0]
+ h.design.Tables["PackEventBattleTable"][0] = testRow(1, 800, 3, 2, 4, 900, 5, 1, 8, 10, 9, 8, 10, 50)
+ h.reject(t, "/QuickBattle", testRow(1, 2, 2, 17, 3, 800, 4, 900, 5, 1, 6, 1))
+ h.design.Tables["PackEventBattleTable"][0] = row
+ h.now = h.now.Add(2 * time.Minute)
+ h.reject(t, "/QuickBattle", testRow(1, 2, 2, 17, 3, 800, 4, 900, 5, 1, 6, 1))
+ after, _ := h.ctx.State.Load("test-wallet")
+ if !bytes.Equal(before, after) {
+ t.Fatal("rejected sweep changed owned assets")
+ }
+}
diff --git a/go/internal/server/domain/events/play/routes.go b/go/internal/server/domain/events/play/routes.go
index 828da76..c0c9b8f 100644
--- a/go/internal/server/domain/events/play/routes.go
+++ b/go/internal/server/domain/events/play/routes.go
@@ -1,6 +1,7 @@
package eventplay
var codes = map[string]int{
+ "/QuickBattle": 261,
"/MiniGameUserRecordInfo": 635,
"/MiniGameRanking": 391,
"/MiniGameRelayServerInfo": 0,
diff --git a/go/internal/server/domain/events/play/single_player.go b/go/internal/server/domain/events/play/single_player.go
index 45a051e..57ec054 100644
--- a/go/internal/server/domain/events/play/single_player.go
+++ b/go/internal/server/domain/events/play/single_player.go
@@ -1,8 +1,10 @@
package eventplay
import (
+ "bd2server/internal/common/util"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/events"
"bd2server/internal/server/protocol/wire"
"fmt"
"math"
@@ -337,15 +339,13 @@ func (s *Service) endSichuan(ctx command.Context, req []byte, a Run, st *snapsho
for _, reward := range s.design.Tables["SichuanRewardTable"] {
group, id := num(reward, 1), num(reward, 2)
count := uint64(0)
- for _, progress := range st.Records {
- if progress.UID != a.UID || progress.Family != a.Family || progress.Mode != group {
- continue
- }
- if group == 2 {
- if progress.Clears["clear"] {
- count++
+ if group == 2 {
+ count = boolWire(clear && a.Mode == group)
+ } else {
+ for _, progress := range st.Records {
+ if progress.UID != a.UID || progress.Family != a.Family || progress.Mode != group {
+ continue
}
- } else {
for i := range 3 {
if progress.Clears[fmt.Sprintf("star:%d", i)] {
count++
@@ -354,7 +354,7 @@ func (s *Service) endSichuan(ctx command.Context, req []byte, a Run, st *snapsho
}
}
identity := fmt.Sprintf("reward:%d:%d", group, id)
- if count < num(reward, 3) || ledger.Clears[identity] {
+ if count < num(reward, 3) || group != 2 && ledger.Clears[identity] {
continue
}
rr, e := gamedata.EventPlayRewards(reward, 6, 5, 4)
@@ -572,11 +572,8 @@ func (s *Service) endRhythm(ctx command.Context, req []byte, a Run, st *snapshot
for typ, count := range counts {
seed += typ * count
}
- random := Run{}
- for i := range random.RandomState {
- random.RandomState[i] = seed + uint64(i)*90
- }
- checksum := fmt.Sprintf("%d-%d-%d-%d", 11111+survivalRandom(&random, 88888), 11111+survivalRandom(&random, 88888), 11111+survivalRandom(&random, 88888), 11111+survivalRandom(&random, 88888))
+ random := util.NewWell512(seed)
+ checksum := fmt.Sprintf("%d-%d-%d-%d", 11111+random.Next()%88888, 11111+random.Next()%88888, 11111+random.Next()%88888, 11111+random.Next()%88888)
checksumWire, _, err := wire.Bytes(req, 5)
if err != nil {
return nil, err
@@ -596,22 +593,10 @@ func (s *Service) endRhythm(ctx command.Context, req []byte, a Run, st *snapshot
r.BestCombo = combo
}
st.Records[recKey(a.UID, a.Stage, a.Mode, a.Family)] = r
- if s.onProgress != nil {
- for typ, count := range counts {
- if count == 0 {
- continue
- }
- if err := s.onProgress(ctx, 49, typ, count); err != nil {
- return nil, err
- }
- }
- for _, p := range []struct{ condition, value, count uint64 }{{51, a.Stage, score}, {52, grade, 1}, {53, a.Mode, 1}, {50, combo, 1}} {
- if p.count == 0 {
- continue
- }
- if err := s.onProgress(ctx, p.condition, p.value, p.count); err != nil {
- return nil, err
- }
+ if s.onRhythmResult != nil && grade > 0 && num(req, 7) == 0 {
+ result := events.RhythmResult{Music: a.Stage, Difficulty: a.Mode, Score: score, Grade: grade, Combo: combo, Judgments: counts}
+ if err := s.onRhythmResult(ctx, result); err != nil {
+ return nil, err
}
}
return wire.AppendBytes(nil, 1, rhythmRecordWire(r)), nil
diff --git a/go/internal/server/domain/events/play/single_player_test.go b/go/internal/server/domain/events/play/single_player_test.go
index 558f502..48ca0f2 100644
--- a/go/internal/server/domain/events/play/single_player_test.go
+++ b/go/internal/server/domain/events/play/single_player_test.go
@@ -254,7 +254,7 @@ func TestSurvivalInsufficientUpgradePreservesStateAndResources(t *testing.T) {
}
}
-func TestSichuanStarsUnlockAndFirstClearRewardsSurviveLogin(t *testing.T) {
+func TestSichuanStarsAndChallengeClearRewardsSurviveLogin(t *testing.T) {
h := newPlayHarness(t)
h.design.Tables["SichuanEventTable"] = [][]byte{testRow(1, 1, 2, 1, 3, 9), testRow(1, 1, 2, 2, 3, 9), testRow(1, 2, 2, 1, 3, 9)}
h.design.Tables["SichuanStageTable"] = [][]byte{testRow(2, 9, 8, 6, 3, 300, 3, 200, 3, 100)}
@@ -283,6 +283,7 @@ func TestSichuanStarsUnlockAndFirstClearRewardsSurviveLogin(t *testing.T) {
if h.balance(t, 27) != 2 {
t.Fatal("normal reward repeated after another level")
}
+ // LocalTextTable 125517 grants furniture for every challenge clear, regardless of rank.
h.call(t, "/MiniGameSichuanStart", start(7, 2, 1))
response := h.call(t, "/MiniGameSichuanEnd", end(8, 180))
if h.balance(t, 27) != 3 {
@@ -293,14 +294,28 @@ func TestSichuanStarsUnlockAndFirstClearRewardsSurviveLogin(t *testing.T) {
t.Fatal("challenge retry duplicated reward")
}
h.call(t, "/MiniGameSichuanStart", start(9, 2, 1))
- h.call(t, "/MiniGameSichuanEnd", end(10, 120))
- if h.balance(t, 27) != 3 {
- t.Fatal("improved challenge time repeated furniture reward")
+ response = h.call(t, "/MiniGameSichuanEnd", end(10, 120))
+ if h.balance(t, 27) != 4 {
+ t.Fatal("second challenge clear did not grant its furniture reward")
+ }
+ h.reopen(t)
+ if !bytes.Equal(response, h.call(t, "/MiniGameSichuanEnd", end(10, 120))) || h.balance(t, 27) != 4 {
+ t.Fatal("second challenge retry duplicated reward")
+ }
+ h.call(t, "/MiniGameSichuanStart", start(11, 2, 1))
+ h.call(t, "/MiniGameSichuanEnd", end(12, 150))
+ if h.balance(t, 27) != 5 {
+ t.Fatal("slower challenge clear did not grant its furniture reward")
+ }
+ h.call(t, "/MiniGameSichuanStart", start(13, 2, 1))
+ h.call(t, "/MiniGameSichuanEnd", wire.AppendVarint(end(14, 150), 2, 1))
+ if h.balance(t, 27) != 5 {
+ t.Fatal("abandoned challenge granted a clear reward")
}
if records := h.service.RankRecords(); len(records) != 1 || records[0].Score != 120 {
t.Fatal("challenge did not retain the smaller clear time")
}
- info := h.call(t, "/MiniGameSichuanInfo", testRow(1, 11, 2, 120))
+ info := h.call(t, "/MiniGameSichuanInfo", testRow(1, 15, 2, 120))
schedule, _, _ := wire.Bytes(info, 1)
var rewardClaims int
_ = wire.Walk(schedule, func(f wire.Field) error {
@@ -417,17 +432,18 @@ func TestRhythmModeRecordsAndClientChecksumPersistIndependently(t *testing.T) {
}
h.call(t, "/MiniGameRhythmPlayStart", testRow(1, 1, 2, 150, 3, 1, 4, 1, 5, 1))
h.reject(t, "/MiniGameRhythmPlayEnd", end(2, 500, 1, 2, "invalid", testRow(1, 1, 2, 2)))
- // Checksums independently evaluated from the client's Well512 game-id recipe.
- first := end(2, 500, 1, 2, "46791-73263-83023-36775", testRow(1, 1, 2, 2))
+ // Four GetRandom(11111, 99999) calls on the official 2.36.7 DLL's Well512,
+ // using seeds 511, 714, and 815 from owner + score + seq + weighted judgments.
+ first := end(2, 500, 1, 2, "46791-93319-66855-91591", testRow(1, 1, 2, 2))
response := h.call(t, "/MiniGameRhythmPlayEnd", first)
h.reopen(t)
if !bytes.Equal(response, h.call(t, "/MiniGameRhythmPlayEnd", first)) {
t.Fatal("rhythm retry changed persisted result")
}
h.call(t, "/MiniGameRhythmPlayStart", testRow(1, 3, 2, 150, 3, 1, 4, 1, 5, 2))
- h.call(t, "/MiniGameRhythmPlayEnd", end(4, 700, 2, 1, "74755-20195-46291-30923", testRow(1, 1, 2, 1), testRow(1, 2, 2, 1)))
+ h.call(t, "/MiniGameRhythmPlayEnd", end(4, 700, 2, 1, "74755-89667-46635-29179", testRow(1, 1, 2, 1), testRow(1, 2, 2, 1)))
h.call(t, "/MiniGameRhythmPlayStart", testRow(1, 5, 2, 150, 3, 1, 4, 1, 5, 0))
- h.call(t, "/MiniGameRhythmPlayEnd", end(6, 800, 1, 2, "82423-77223-39783-63487", testRow(1, 1, 2, 2)))
+ h.call(t, "/MiniGameRhythmPlayEnd", end(6, 800, 1, 2, "82423-43279-74967-75511", testRow(1, 1, 2, 2)))
h.reopen(t)
records := h.service.RankRecords()
if len(records) != 2 {
diff --git a/go/internal/server/domain/events/play/survival.go b/go/internal/server/domain/events/play/survival.go
index f98cab2..c4d053c 100644
--- a/go/internal/server/domain/events/play/survival.go
+++ b/go/internal/server/domain/events/play/survival.go
@@ -1,6 +1,7 @@
package eventplay
import (
+ "bd2server/internal/common/util"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/protocol/wire"
@@ -115,9 +116,8 @@ func (s *Service) startSurvival(req []byte, a *Run, st *snapshot) error {
a.SpecialItems = map[uint64]uint64{}
a.Skills = []uint64{num(char, 3)}
a.SkillLevels = map[uint64]uint64{num(char, 3): 1}
- for i := range a.RandomState {
- a.RandomState[i] = seqSeed(a.Started) + uint64(i)*90
- }
+ random := util.NewWell512(seqSeed(a.Started))
+ a.RandomState, a.RandomIndex = random.State, random.Index
return nil
}
@@ -169,25 +169,6 @@ func (s *Service) collectSurvival(st *snapshot, a Run, typ, value uint64) {
st.Records[recKey(a.UID, 0, 0, a.Family)] = ledger
}
-func survivalRandom(a *Run, bound uint64) uint64 {
- index := a.RandomIndex
- x, y := a.RandomState[index], a.RandomState[(index+13)&15]
- b := x ^ y ^ (x << 16) ^ (y << 15)
- c := a.RandomState[(index+9)&15]
- c ^= c >> 11
- x = b ^ c
- a.RandomState[index] = x
- d := x ^ ((x << 5) & uint64(0xffffffffda442d24))
- index = (index + 15) & 15
- x = a.RandomState[index]
- a.RandomState[index] = x ^ b ^ d ^ (x << 2) ^ (b << 18) ^ (c << 28)
- a.RandomIndex = index
- if bound == 0 {
- bound = 1
- }
- return uint64(float32(a.RandomState[index] % bound))
-}
-
func (s *Service) survivalDropBox(a *Run, id uint64) error {
row, err := s.design.Row("FieldMiniGameSurvivalBoxTable", 2, id)
if err != nil {
@@ -212,7 +193,9 @@ func (s *Service) survivalDropBox(a *Run, id uint64) error {
if total == 0 {
return fmt.Errorf("eventplay: empty survival drop ratios")
}
- draw := survivalRandom(a, total)
+ random := util.Well512{State: a.RandomState, Index: a.RandomIndex}
+ draw := uint64(float32(random.Next() % total))
+ a.RandomState, a.RandomIndex = random.State, random.Index
for i, weight := range ratios {
if draw < weight {
items = []uint64{items[i]}
diff --git a/go/internal/server/domain/events/protocol_adapter.go b/go/internal/server/domain/events/protocol_adapter.go
index 4568f1f..eb65295 100644
--- a/go/internal/server/domain/events/protocol_adapter.go
+++ b/go/internal/server/domain/events/protocol_adapter.go
@@ -198,6 +198,10 @@ func (e *Economy) Apply(ctx command.Context, identity string, costs, rewards []g
})
for _, k := range keys {
n := totals[k]
+ if lifeCurrency(k[0]) {
+ selected = append(selected, assets.Item{Type: k[0], ID: k[1], Count: n})
+ continue
+ }
if walletCurrency(k[0]) || extraCurrency(k[0]) || apCurrency(k[0]) {
if k[1] != 0 {
return nil, fmt.Errorf("events: currency has item id")
@@ -249,13 +253,18 @@ func (e *Economy) consumeAndGrant(ctx command.Context, identity string, consumed
return nil, err
}
var itemCosts []assets.Item
- var walletCosts, apCosts []gamedata.Reward
+ var walletCosts, apCosts, lifeCosts []gamedata.Reward
for _, c := range consumed {
if c.Count == 0 || c.Count > math.MaxInt32 {
return nil, fmt.Errorf("events: invalid consumption count")
}
r := gamedata.Reward{Type: c.Type, ID: c.ID, Count: c.Count}
switch {
+ case lifeCurrency(c.Type):
+ if c.InvenIndex != 0 {
+ return nil, fmt.Errorf("events: invalid life cost index")
+ }
+ lifeCosts = append(lifeCosts, r)
case walletCurrency(c.Type):
if c.ID != 0 || c.InvenIndex != 0 {
return nil, fmt.Errorf("events: invalid currency cost")
@@ -296,7 +305,7 @@ func (e *Economy) consumeAndGrant(ctx command.Context, identity string, consumed
if err != nil {
return nil, err
}
- var walletRewards, apRewards, buffItems []gamedata.Reward
+ var walletRewards, apRewards, buffItems, lifeRewards []gamedata.Reward
var itemRewards []gamedata.BattleReward
var costumes []uint64
var equips []assets.Equipment
@@ -306,6 +315,8 @@ func (e *Economy) consumeAndGrant(ctx command.Context, identity string, consumed
return nil, fmt.Errorf("events: invalid reward count")
}
switch {
+ case lifeCurrency(r.Type):
+ lifeRewards = append(lifeRewards, gamedata.Reward(r))
case walletCurrency(r.Type):
if r.ID != 0 {
return nil, fmt.Errorf("events: currency reward has item id")
@@ -399,6 +410,14 @@ func (e *Economy) consumeAndGrant(ctx command.Context, identity string, consumed
return nil, err
}
}
+ if len(lifeCosts)+len(lifeRewards) != 0 {
+ if e.life == nil {
+ return nil, fmt.Errorf("events: life economy unavailable")
+ }
+ if err := e.life.CanApply(ctx, lifeCosts, lifeRewards); err != nil {
+ return nil, err
+ }
+ }
// Validation and random generation finish before the first account write.
if len(itemCosts) > 0 {
if err = e.items.Consume(ctx, itemCosts); err != nil {
@@ -418,6 +437,13 @@ func (e *Economy) consumeAndGrant(ctx command.Context, identity string, consumed
return nil, err
}
}
+ if len(lifeCosts)+len(lifeRewards) != 0 {
+ lifeBundle, err := e.life.Apply(ctx, identity+":life", lifeCosts, lifeRewards)
+ if err != nil {
+ return nil, err
+ }
+ bundle = append(bundle, lifeBundle...)
+ }
items, err := e.items.GrantOnce(ctx, identity+":items", itemRewards)
if err != nil {
return nil, err
@@ -469,6 +495,10 @@ func (e *Economy) OpenBox(ctx command.Context, identity string, box assets.Item)
}
func (s *BoxService) Handle(ctx command.Context, path string, req []byte) (int, []byte, bool, error) {
+ if path == "/UseResourceItem" {
+ out, err := s.useResource(ctx, req)
+ return 271, out, true, err
+ }
commandSession := ctx.SessionID
if path != "/UseRandomBox" {
return 0, nil, false, nil
@@ -545,7 +575,7 @@ func (e *Economy) ChargeInfo(ctx command.Context) ([]byte, error) {
return nil, err
}
var out []byte
- for _, typ := range []uint64{30, 32} {
+ for _, typ := range []uint64{30, 32, 35} {
if _, ok := e.apCaps[typ]; !ok {
continue
}
diff --git a/go/internal/server/domain/events/registry.go b/go/internal/server/domain/events/registry.go
index 92a3b7c..ab4199c 100644
--- a/go/internal/server/domain/events/registry.go
+++ b/go/internal/server/domain/events/registry.go
@@ -12,6 +12,11 @@ type Schedule struct {
Start, End int64
}
+type RhythmResult struct {
+ Music, Difficulty, Score, Grade, Combo uint64
+ Judgments map[uint64]uint64
+}
+
// Resolver separates gameplay from the project's published calendar.
type Resolver interface {
Resolve(uid uint64) (Schedule, error)
diff --git a/go/internal/server/domain/events/resource_items.go b/go/internal/server/domain/events/resource_items.go
new file mode 100644
index 0000000..4098572
--- /dev/null
+++ b/go/internal/server/domain/events/resource_items.go
@@ -0,0 +1,88 @@
+package events
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/json"
+ "fmt"
+ "math"
+ "strconv"
+
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/protocol/wire"
+)
+
+func (s *BoxService) useResource(ctx command.Context, req []byte) ([]byte, error) {
+ if s.resources == nil || ctx.SessionID == "" {
+ return nil, fmt.Errorf("events: resource item service unavailable")
+ }
+ var values [4]uint64
+ seen := map[int]bool{}
+ if err := wire.Walk(req, func(f wire.Field) error {
+ if f.Number > 4 {
+ return nil
+ }
+ if f.Type != 0 || seen[f.Number] {
+ return fmt.Errorf("events: invalid resource request field")
+ }
+ seen[f.Number] = true
+ values[f.Number-1], _ = binary.Uvarint(f.Value)
+ return nil
+ }); err != nil {
+ return nil, err
+ }
+ seq, index, count, choice := values[0], values[1], values[2], values[3]
+ if seq == 0 || seq > math.MaxInt32 || index == 0 || index > math.MaxInt64 || count == 0 || count > math.MaxInt32 || choice == 0 || choice > math.MaxInt32 {
+ return nil, fmt.Errorf("events: invalid resource request")
+ }
+ key := "resource:" + ctx.SessionID + ":" + strconv.FormatUint(seq, 10)
+ receipts := map[string]boxReceipt{}
+ raw, err := s.store.Load(ctx.State, "eventboxes")
+ if err != nil {
+ return nil, err
+ }
+ if raw != nil {
+ if err := json.Unmarshal(raw, &receipts); err != nil {
+ return nil, err
+ }
+ if receipts == nil {
+ return nil, fmt.Errorf("events: invalid resource receipts")
+ }
+ }
+ if r, ok := receipts[key]; ok {
+ if !bytes.Equal(r.Request, req) {
+ return nil, fmt.Errorf("events: resource sequence conflict")
+ }
+ return bytes.Clone(r.Response), nil
+ }
+ var item assets.Item
+ for _, candidate := range s.items.All(ctx) {
+ if candidate.InvenIndex == index {
+ item = candidate
+ break
+ }
+ }
+ if item.Type != 8 || item.Count < count {
+ return nil, fmt.Errorf("events: resource item unavailable")
+ }
+ rewards, err := s.resources.Select(item.ID, choice, count)
+ if err != nil {
+ return nil, err
+ }
+ item.Count = count
+ bundle, err := s.economy.ConsumeAndGrant(ctx, "use:"+key, []assets.Item{item}, rewards)
+ if err != nil {
+ return nil, err
+ }
+ out := wire.AppendBytes(nil, 1, bundle)
+ receipts[key] = boxReceipt{bytes.Clone(req), bytes.Clone(out)}
+ raw, err = json.Marshal(receipts)
+ if err != nil {
+ return nil, err
+ }
+ if err := s.store.Save(ctx.State, "eventboxes", raw); err != nil {
+ return nil, err
+ }
+ return out, nil
+}
diff --git a/go/internal/server/domain/events/resource_items_test.go b/go/internal/server/domain/events/resource_items_test.go
new file mode 100644
index 0000000..89ec6a7
--- /dev/null
+++ b/go/internal/server/domain/events/resource_items_test.go
@@ -0,0 +1,180 @@
+package events
+
+import (
+ "bytes"
+ "context"
+ "path/filepath"
+ "testing"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/protocol/wire"
+ accountstate "bd2server/internal/server/storage/account"
+ "bd2server/internal/server/storage/stateio"
+)
+
+type resourceCostumes struct{}
+
+func (resourceCostumes) Character(id uint64) (gamedata.CharacterDesign, bool) {
+ return gamedata.CharacterDesign{ID: 77, HP: 100, CostumeMaxLevel: 1, OverflowItemType: 20, OverflowItemCount: 10}, id == 701
+}
+
+type resourceGraph struct{}
+
+func (resourceGraph) Resolve(r []gamedata.BattleReward) ([]gamedata.BattleReward, error) {
+ return r, nil
+}
+
+type resourceOptions struct{}
+
+func (resourceOptions) RollOptions(uint64) ([]gamedata.EquipmentOptionChoice, []gamedata.EquipmentOptionChoice, *gamedata.EquipmentOptionChoice, error) {
+ return nil, nil, nil, nil
+}
+
+type resourceRuntime struct {
+ ctx command.Context
+ box *BoxService
+ items *assets.Inventory
+ wallet *assets.Wallet
+ collection *roster.CollectionStore
+}
+
+func openResourceRuntime(t *testing.T, state stateio.AtomicEntryStore, initial bool) resourceRuntime {
+ t.Helper()
+ ctx := command.Context{Identity: command.Identity{AccountID: "selector", SessionID: "login"}, State: state}
+ store := stateio.RootStore{}
+ items, err := assets.OpenInventory(ctx, store, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if initial {
+ if err := items.InitializeItems(ctx, []assets.Item{{InvenIndex: 900000010, Type: 8, ID: 501, Count: 4}, {InvenIndex: 900000011, Type: 8, ID: 502, Count: 1}, {InvenIndex: 900000012, Type: 9, ID: 501, Count: 1}}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ wallet, err := assets.OpenWallet(ctx, store, assets.Currency{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ collection, err := roster.OpenCollectionStore(ctx, store, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ equipment, err := assets.OpenEquipmentInventory(ctx, store)
+ if err != nil {
+ t.Fatal(err)
+ }
+ gameplay := stateio.EntrySnapshotStore{Domain: "collection", Bucket: "gameplay"}
+ economy, err := NewEconomy(ctx, gameplay, items, wallet, collection, equipment, resourceCostumes{}, resourceOptions{}, resourceGraph{}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ box, err := OpenBoxes(gameplay, items, economy)
+ if err != nil {
+ t.Fatal(err)
+ }
+ box.AttachResourceItems(&gamedata.ResourceItemDesign{Selections: map[uint64]map[uint64]gamedata.BattleReward{501: {701: {Type: 11, ID: 701, Count: 1}}}})
+ return resourceRuntime{ctx, box, items, wallet, collection}
+}
+
+func resourceRequest(seq, index, count, selection uint64) []byte {
+ b := wire.AppendVarint(nil, 1, seq)
+ b = wire.AppendVarint(b, 2, index)
+ b = wire.AppendVarint(b, 3, count)
+ return wire.AppendVarint(b, 4, selection)
+}
+
+func (r resourceRuntime) use(t *testing.T, req []byte) []byte {
+ t.Helper()
+ code, out, handled, err := r.box.Handle(r.ctx, "/UseResourceItem", req)
+ if err != nil || !handled || code != 271 {
+ t.Fatalf("use resource failed: %d %v", code, err)
+ }
+ return out
+}
+
+func TestResourceChoiceConsumesInventoryAndRestoresCostumeUpgradeAndOverflow(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "state.db")
+ repo, err := accountstate.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = repo.Close() }()
+ tx, err := repo.BeginCommand(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := openResourceRuntime(t, tx, true)
+ req := resourceRequest(1, 900000010, 3, 701)
+ first := r.use(t, req)
+ if len(r.collection.Costumes()) != 1 || len(r.collection.Characters()) != 1 || r.collection.Costumes()[0].ID != 701 || r.collection.Costumes()[0].Level != 1 || r.wallet.Snapshot(r.ctx).Mileage != 10 {
+ t.Fatal("choice did not create, upgrade then exchange the selected costume")
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ if err := repo.Close(); err != nil {
+ t.Fatal(err)
+ }
+ repo, err = accountstate.Open(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tx, err = repo.BeginCommand(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() { _ = tx.Rollback() }()
+ r = openResourceRuntime(t, tx, false)
+ if !bytes.Equal(first, r.use(t, req)) {
+ t.Fatal("retry after database reopen changed resource response")
+ }
+ if r.wallet.Snapshot(r.ctx).Mileage != 10 || len(r.collection.Costumes()) != 1 || r.collection.Costumes()[0].Level != 1 {
+ t.Fatal("reopened retry duplicated selected rewards")
+ }
+ remaining := uint64(0)
+ for _, item := range r.items.All(r.ctx) {
+ if item.InvenIndex == 900000010 {
+ remaining = item.Count
+ }
+ }
+ if remaining != 1 {
+ t.Fatalf("ticket consumption lost or duplicated after reopen: %d", remaining)
+ }
+ r.use(t, resourceRequest(2, 900000010, 1, 701))
+ if r.wallet.Snapshot(r.ctx).Mileage != 20 {
+ t.Fatal("new request did not consume final ticket and exchange the maxed costume")
+ }
+}
+
+func TestResourceChoiceRejectsInvalidSelectionsAndCannotUseAnotherAccountInventory(t *testing.T) {
+ state := stateio.NewMemory()
+ r := openResourceRuntime(t, state, true)
+ for _, req := range [][]byte{
+ resourceRequest(1, 900000010, 0, 701), resourceRequest(1, 900000010, 5, 701),
+ resourceRequest(1, 900000010, 1, 702), resourceRequest(1, 900000011, 1, 701),
+ resourceRequest(1, 900000012, 1, 701), resourceRequest(1, 123, 1, 701),
+ wire.AppendVarint(resourceRequest(1, 900000010, 1, 701), 4, 701),
+ } {
+ if _, _, _, err := r.box.Handle(r.ctx, "/UseResourceItem", req); err == nil {
+ t.Fatal("invalid resource use succeeded")
+ }
+ }
+ if len(r.collection.Costumes()) != 0 || r.items.All(r.ctx)[0].Count != 4 || r.wallet.Snapshot(r.ctx).Mileage != 0 {
+ t.Fatal("rejected requests changed owned assets")
+ }
+ r.use(t, resourceRequest(9, 900000010, 1, 701))
+ if _, _, _, err := r.box.Handle(r.ctx, "/UseResourceItem", resourceRequest(9, 900000010, 2, 701)); err == nil {
+ t.Fatal("sequence conflict consumed more tickets")
+ }
+ other := openResourceRuntime(t, stateio.NewMemory(), false)
+ other.ctx.AccountID = "other"
+ if _, _, _, err := other.box.Handle(other.ctx, "/UseResourceItem", resourceRequest(1, 900000010, 1, 701)); err == nil {
+ t.Fatal("another account used the selector's ticket")
+ }
+ if len(other.collection.Costumes()) != 0 || len(other.items.All(other.ctx)) != 0 {
+ t.Fatal("rejected cross-account use created assets")
+ }
+}
diff --git a/go/internal/server/domain/events/roguelike_ap_test.go b/go/internal/server/domain/events/roguelike_ap_test.go
new file mode 100644
index 0000000..ee4bd73
--- /dev/null
+++ b/go/internal/server/domain/events/roguelike_ap_test.go
@@ -0,0 +1,76 @@
+package events
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/roster"
+ "bd2server/internal/server/storage/stateio"
+ "encoding/json"
+ "testing"
+ "time"
+)
+
+// ScheduleElement.GetCostChargeTime selects daily reset for free RogueLike
+// tickets. Existing zero balances mean spent tickets, not an unclaimed grant.
+func TestNewRogueTicketAllowanceDoesNotRefillBeforeDailyReset(t *testing.T) {
+ store := stateio.NewMemory()
+ ctx := command.Context{State: store}
+ now := time.Date(2026, 10, 18, 10, 0, 0, 0, time.UTC)
+ e := &Economy{store: stateio.EntrySnapshotStore{Domain: "battle", Bucket: "gameplay"}, initial: map[uint64]uint64{35: 0}}
+ wallet, err := assets.OpenWallet(ctx, stateio.RootStore{}, assets.Currency{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ items, err := assets.OpenInventory(ctx, stateio.RootStore{}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ collection, err := roster.OpenCollectionStore(ctx, stateio.RootStore{}, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ equipment, err := assets.OpenEquipmentInventory(ctx, stateio.RootStore{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ e, err = NewEconomy(ctx, e.store, items, wallet, collection, equipment, resourceCostumes{}, resourceOptions{}, resourceGraph{}, map[uint64]uint64{35: 0})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := e.AttachAPRefresh(map[uint64]uint64{35: 10}, gamedata.HuntingAPDesign{ResetSeconds: 9 * 3600}); err != nil {
+ t.Fatal(err)
+ }
+ e.now = func() time.Time { return now }
+ raw, _ := json.Marshal(economySnapshot{Balances: map[uint64]uint64{38: 3}, Receipts: map[string]economyReceipt{}})
+ if err := e.store.Save(ctx.State, "event_economy", raw); err != nil {
+ t.Fatal(err)
+ }
+ clock, _ := json.Marshal(economyAPClock{Next: time.Date(2026, 10, 19, 0, 0, 0, 0, time.UTC).UnixMilli()})
+ if err := e.store.Save(ctx.State, "eventapclock", clock); err != nil {
+ t.Fatal(err)
+ }
+ balance, err := e.CurrencyBalance(ctx, 35)
+ if err != nil || balance != 10 {
+ t.Fatalf("new allowance: %d %v", balance, err)
+ }
+ if _, err = e.Apply(ctx, "rogue-entry-tickets", []gamedata.Reward{{Type: 35, Count: 10}}, nil); err != nil {
+ t.Fatal(err)
+ }
+ for range 2 {
+ reopened := *e
+ balance, err = reopened.CurrencyBalance(ctx, 35)
+ if err != nil || balance != 0 {
+ t.Fatalf("spent tickets refilled before reset: %d %v", balance, err)
+ }
+ }
+ now = now.Add(24 * time.Hour)
+ balance, err = e.CurrencyBalance(ctx, 35)
+ if err != nil || balance != 10 {
+ t.Fatalf("daily reset did not restore allowance: %d %v", balance, err)
+ }
+ paid, err := e.CurrencyBalance(ctx, 38)
+ if err != nil || paid != 3 {
+ t.Fatal("free reset changed paid ticket stack")
+ }
+}
diff --git a/go/internal/server/domain/events/tasks/passes.go b/go/internal/server/domain/events/tasks/passes.go
new file mode 100644
index 0000000..135b4be
--- /dev/null
+++ b/go/internal/server/domain/events/tasks/passes.go
@@ -0,0 +1,49 @@
+package eventtasks
+
+import (
+ "math"
+ "slices"
+
+ "bd2server/internal/server/domain/events"
+)
+
+func (s *Service) passSchedules() []events.Schedule {
+ permanent := make([]uint64, 0)
+ for id, design := range s.design.Passes {
+ if design.ScheduleType == 0 && design.NewbieGroup > 0 && design.NewbieStep > 0 {
+ permanent = append(permanent, id)
+ }
+ }
+ rows := slices.DeleteFunc(s.registry.List(), func(row events.Schedule) bool {
+ return row.Type == 5 && slices.Contains(permanent, row.ID)
+ })
+ slices.Sort(permanent)
+ for _, id := range permanent {
+ // Permanent guide passes have a stable local identity, not a public
+ // event calendar entry. The native PassInfo includes them directly.
+ rows = append(rows, events.Schedule{Type: 5, ID: id, End: math.MaxInt64})
+ }
+ return rows
+}
+
+func (s *Service) reconcileGuidePass(v events.Schedule) {
+ design := s.design.Passes[v.ID]
+ if design.ScheduleType != 0 || design.NewbieGroup == 0 || design.NewbieStep == 0 {
+ return
+ }
+ missionSchedule, err := s.find(4, design.MissionGroup)
+ if err != nil {
+ return
+ }
+ var earned uint64
+ for _, task := range s.design.Missions {
+ if !slices.Contains(s.design.MissionGroups[design.MissionGroup].Groups, task.Group) {
+ continue
+ }
+ if progress := s.state.Missions[scheduleKey(missionSchedule)+"/"+key(task.ID)]; progress != nil && progress.Claimed {
+ earned += task.PassExp
+ }
+ }
+ progress := s.pass(v)
+ progress.Exp = max(progress.Exp, earned)
+}
diff --git a/go/internal/server/domain/events/tasks/protocol_adapter.go b/go/internal/server/domain/events/tasks/protocol_adapter.go
index b158156..97f740c 100644
--- a/go/internal/server/domain/events/tasks/protocol_adapter.go
+++ b/go/internal/server/domain/events/tasks/protocol_adapter.go
@@ -9,6 +9,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "math"
"slices"
"sort"
"strconv"
@@ -277,14 +278,20 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st
id, value, event := scalar(f.Value, 2), scalar(f.Value, 3), scalar(f.Value, 4)
v, e := s.find(4, event)
if e != nil {
- return e
+ return fmt.Errorf("eventtasks: mission update event=%d group=%d mission=%d: %w", event, scalar(f.Value, 1), id, e)
}
t, ok := s.design.Missions[id]
- if !ok || t.Group != scalar(f.Value, 1) || !s.availableTask(ctx, v, t) {
- return errors.New("eventtasks: invalid mission update")
+ if !ok || t.Group != scalar(f.Value, 1) || !s.availableTask(ctx, v, t) || value > math.MaxInt32 {
+ return fmt.Errorf("eventtasks: invalid mission update event=%d group=%d mission=%d value=%d", event, scalar(f.Value, 1), id, value)
}
- if value > s.mission(v, id).Value {
- return errors.New("eventtasks: client progress exceeds authoritative gameplay")
+ m := s.mission(v, id)
+ progress := min(value, t.Target)
+ // Homescreen slots are saved in ClientLocalInfo; MissionUpdate is
+ // the native client's only server notification of this UI action.
+ if t.Type == 39 && t.SubType == 0 && (len(t.Params) == 0 || slices.Contains(t.Params, uint64(0))) {
+ m.Value = max(m.Value, progress)
+ } else if progress > m.Value {
+ return fmt.Errorf("eventtasks: client progress exceeds authoritative gameplay event=%d group=%d mission=%d condition=%d subtype=%d client=%d authoritative=%d target=%d", event, t.Group, id, t.Type, t.SubType, value, m.Value, t.Target)
}
return nil
})
@@ -352,7 +359,7 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st
m.Value = completed
}
}
- for _, pv := range s.registry.List() {
+ for _, pv := range s.passSchedules() {
if pv.Type == 5 && s.active(pv) && s.design.Passes[pv.ID].MissionGroup == v.ID {
s.pass(pv).Exp += exp
}
@@ -360,10 +367,11 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st
return wire.AppendBytes(nil, 1, bundle), nil
case "/PassInfo":
var out []byte
- for _, v := range s.registry.List() {
+ for _, v := range s.passSchedules() {
if v.Type != 5 || !s.active(v) {
continue
}
+ s.reconcileGuidePass(v)
p := s.pass(v)
x := wire.AppendVarint(nil, 1, v.ID)
x = wire.AppendVarint(x, 2, p.Exp)
@@ -398,9 +406,10 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st
if !ok {
return nil, errors.New("eventtasks: unknown pass")
}
+ s.reconcileGuidePass(v)
p := s.pass(v)
if d.NewbieStep > s.state.NewbieStep {
- return nil, errors.New("eventtasks: guide pass step locked")
+ return nil, fmt.Errorf("eventtasks: guide pass step locked pass=%d step=%d unlocked_step=%d", v.ID, d.NewbieStep, s.state.NewbieStep)
}
all, id, rt := scalar(b, 2) != 0, scalar(b, 4), scalar(b, 5)
if rt > 1 {
@@ -479,6 +488,7 @@ func (s *Service) handle(ctx command.Context, path string, b []byte, identity st
if e != nil {
return nil, e
}
+ s.reconcileGuidePass(v)
p := s.pass(v)
typ := scalar(b, 3)
var chosen *gamedata.EventPassBuy
diff --git a/go/internal/server/domain/events/tasks/rhythm.go b/go/internal/server/domain/events/tasks/rhythm.go
new file mode 100644
index 0000000..70f5906
--- /dev/null
+++ b/go/internal/server/domain/events/tasks/rhythm.go
@@ -0,0 +1,86 @@
+package eventtasks
+
+import (
+ "slices"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/events"
+)
+
+func (s *Service) RecordRhythmResult(ctx command.Context, result events.RhythmResult) error {
+ changed := false
+ for _, schedule := range s.taskSchedules() {
+ if schedule.Type != 4 || !s.active(schedule) {
+ continue
+ }
+ for _, task := range s.design.Missions {
+ if !s.availableTask(ctx, schedule, task) || !rhythmTaskSatisfied(task, result) {
+ continue
+ }
+ progress := s.mission(schedule, task.ID)
+ if progress.Claimed || progress.Value >= task.Target {
+ continue
+ }
+ progress.Value++
+ changed = true
+ }
+ }
+ if !changed {
+ return nil
+ }
+ return s.save(ctx)
+}
+
+func (s *Service) ReconcileRhythmResults(ctx command.Context, results []events.RhythmResult) error {
+ changed := false
+ for _, schedule := range s.taskSchedules() {
+ if schedule.Type != 4 || !s.active(schedule) {
+ continue
+ }
+ group := s.design.MissionGroups[schedule.ID]
+ if group.Type != 0 || group.ScheduleType != 0 {
+ continue
+ }
+ for _, task := range s.design.Missions {
+ if task.Type < 49 || task.Type > 53 || !s.availableTask(ctx, schedule, task) {
+ continue
+ }
+ var value uint64
+ for _, result := range results {
+ if rhythmTaskSatisfied(task, result) {
+ value++
+ }
+ }
+ value = min(value, task.Target)
+ if value == 0 {
+ continue
+ }
+ progress := s.mission(schedule, task.ID)
+ if !progress.Claimed && value > progress.Value {
+ progress.Value = value
+ changed = true
+ }
+ }
+ }
+ if !changed {
+ return nil
+ }
+ return s.save(ctx)
+}
+
+func rhythmTaskSatisfied(task gamedata.EventTask, result events.RhythmResult) bool {
+ switch task.Type {
+ case 49:
+ return len(task.Params) == 1 && result.Judgments[task.SubType] >= task.Params[0]
+ case 50:
+ return task.SubType == result.Music && result.Combo > 0
+ case 51:
+ return result.Score >= task.SubType
+ case 52:
+ return task.SubType == result.Music && len(task.Params) == 1 && result.Grade > 0 && result.Grade <= task.Params[0]
+ case 53:
+ return task.SubType == result.Music && slices.Contains(task.Params, result.Difficulty)
+ }
+ return false
+}
diff --git a/go/internal/server/domain/events/tasks/service.go b/go/internal/server/domain/events/tasks/service.go
index 972a0d4..8086ca1 100644
--- a/go/internal/server/domain/events/tasks/service.go
+++ b/go/internal/server/domain/events/tasks/service.go
@@ -198,8 +198,11 @@ func (s *Service) active(v events.Schedule) bool {
}
func (s *Service) find(t, id uint64) (events.Schedule, error) {
rows := s.registry.List()
- if t == 4 {
+ switch t {
+ case 4:
rows = s.taskSchedules()
+ case 5:
+ rows = s.passSchedules()
}
for _, v := range rows {
if v.Type == t && v.ID == id && s.active(v) {
diff --git a/go/internal/server/domain/fishing/fishing.go b/go/internal/server/domain/fishing/fishing.go
index 430e6d4..99eb09c 100644
--- a/go/internal/server/domain/fishing/fishing.go
+++ b/go/internal/server/domain/fishing/fishing.go
@@ -1,14 +1,13 @@
package fishing
import (
+ "bd2server/internal/common/util"
"bytes"
- "crypto/rand"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"math"
- "math/big"
"slices"
"strconv"
"time"
@@ -188,11 +187,7 @@ func sample(max uint64) (uint64, error) {
if max == 0 {
return 0, fmt.Errorf("fishing: empty pool")
}
- n, e := rand.Int(rand.Reader, new(big.Int).SetUint64(max))
- if e != nil {
- return 0, e
- }
- return n.Uint64(), nil
+ return util.RandomUint64N(max)
}
func num(b []byte, n int) uint64 { v, _, _ := wire.Varint(b, n); return v }
func dbl(b []byte, n int) float64 {
diff --git a/go/internal/server/domain/identity/service.go b/go/internal/server/domain/identity/service.go
index 07952dc..04e3db2 100644
--- a/go/internal/server/domain/identity/service.go
+++ b/go/internal/server/domain/identity/service.go
@@ -1,9 +1,8 @@
package identity
import (
+ "bd2server/internal/common/util"
"context"
- "crypto/rand"
- "encoding/base64"
"errors"
"time"
)
@@ -47,26 +46,19 @@ func New(config Config, store Repository) (*Service, error) {
return &Service{config: config, store: store}, nil
}
func (s *Service) Now() time.Time { return s.store.Now() }
-func randomToken(size int) (string, error) {
- b := make([]byte, size)
- if _, e := rand.Read(b); e != nil {
- return "", e
- }
- return base64.RawURLEncoding.EncodeToString(b), nil
-}
func (s *Service) CreateDevice(provider, clientIP string) (CreatedDevice, error) {
if _, ok := s.config.Providers[provider]; !ok {
return CreatedDevice{}, failure(Invalid, "provider is not enabled")
}
- id, e := randomToken(18)
+ id, e := util.RandomBase64URL(18)
if e != nil {
return CreatedDevice{}, e
}
- secret, e := randomToken(32)
+ secret, e := util.RandomBase64URL(32)
if e != nil {
return CreatedDevice{}, e
}
- ticket, e := randomToken(32)
+ ticket, e := util.RandomBase64URL(32)
if e != nil {
return CreatedDevice{}, e
}
@@ -102,15 +94,15 @@ func (s *Service) Start(provider, id, ticket string) (Authorization, error) {
if s.Now().Unix() >= row.Expires {
return Authorization{}, failure(Expired, "login transaction expired")
}
- state, e := randomToken(32)
+ state, e := util.RandomBase64URL(32)
if e != nil {
return Authorization{}, e
}
- verifier, e := randomToken(32)
+ verifier, e := util.RandomBase64URL(32)
if e != nil {
return Authorization{}, e
}
- nonce, e := randomToken(24)
+ nonce, e := util.RandomBase64URL(24)
if e != nil {
return Authorization{}, e
}
@@ -203,7 +195,7 @@ func (s *Service) CompleteDevice(deviceID, provider string, id ProviderIdentity)
if e != nil {
return e
}
- account.ID, e = randomToken(18)
+ account.ID, e = util.RandomBase64URL(18)
if e != nil {
return e
}
@@ -222,15 +214,15 @@ func (s *Service) CompleteDevice(deviceID, provider string, id ProviderIdentity)
if account.Status != "active" {
return reject()
}
- family, e := randomToken(18)
+ family, e := util.RandomBase64URL(18)
if e != nil {
return e
}
- access, e := randomToken(32)
+ access, e := util.RandomBase64URL(32)
if e != nil {
return e
}
- refresh, e := randomToken(32)
+ refresh, e := util.RandomBase64URL(32)
if e != nil {
return e
}
@@ -351,11 +343,11 @@ func (s *Service) Refresh(token, attemptID string) (TokenSet, error) {
}
return TokenSet{}, invalidRefresh(Unauthorized, "refresh token replayed")
}
- access, e := randomToken(32)
+ access, e := util.RandomBase64URL(32)
if e != nil {
return TokenSet{}, e
}
- refresh, e := randomToken(32)
+ refresh, e := util.RandomBase64URL(32)
if e != nil {
return TokenSet{}, e
}
diff --git a/go/internal/server/domain/inventory/owned.go b/go/internal/server/domain/inventory/owned.go
index e8ec719..a1797db 100644
--- a/go/internal/server/domain/inventory/owned.go
+++ b/go/internal/server/domain/inventory/owned.go
@@ -19,15 +19,16 @@ import (
// Inventory holds player-owned rewards separately from the immutable starter
// seed. GrantOnce uses a battle identity to prevent double-credit on retries.
type Inventory struct {
- store stateio.ScopedEntryStore
- starter []Item
- randomBoxes *gamedata.RandomBoxDesign
- itemStacks *gamedata.ItemStackDesign
- owned ownedSnapshot
- persisted ownedSnapshot
- capacity *InventorySlots
- discard map[uint64]func(command.Context, Item) error
- corePresent bool
+ store stateio.ScopedEntryStore
+ starter []Item
+ randomBoxes *gamedata.RandomBoxDesign
+ prestigeIllustrations map[uint64]uint64
+ itemStacks *gamedata.ItemStackDesign
+ owned ownedSnapshot
+ persisted ownedSnapshot
+ capacity *InventorySlots
+ discard map[uint64]func(command.Context, Item) error
+ corePresent bool
}
type ownedSnapshot struct {
@@ -220,7 +221,7 @@ func (s *Inventory) GrantOnce(ctx command.Context, identity string, rewards []ga
return nil, err
}
s.owned = next
- return newItems, nil
+ return s.withPrestigeIllustrations(newItems), nil
}
func cloneOwnedSnapshot(current ownedSnapshot) ownedSnapshot {
@@ -319,7 +320,7 @@ func equalItem(a, b Item) bool { return reflect.DeepEqual(a, b) }
// Legacy grants made before instance tracking return an empty slice.
func (s *Inventory) GrantedItems(identity string) []Item {
if rewards, found := s.owned.GrantRewards[identity]; found {
- return append([]Item(nil), rewards...)
+ return s.withPrestigeIllustrations(append([]Item(nil), rewards...))
}
indexes := s.owned.GrantItems[identity]
result := make([]Item, 0, len(indexes))
@@ -331,7 +332,7 @@ func (s *Inventory) GrantedItems(identity string) []Item {
}
}
}
- return result
+ return s.withPrestigeIllustrations(result)
}
// WasGranted reports whether GrantOnce committed the identity even when all
diff --git a/go/internal/server/domain/inventory/preset_runtime.go b/go/internal/server/domain/inventory/preset_runtime.go
index 5f37b78..59d1e24 100644
--- a/go/internal/server/domain/inventory/preset_runtime.go
+++ b/go/internal/server/domain/inventory/preset_runtime.go
@@ -65,3 +65,8 @@ func (s *EquipmentInventory) ValidatePresetEquipment(ctx command.Context, bindin
// ApplyPresetCostumes changes the currently selected costume for each listed
// character and persists both seeded and collection-owned character records.
+
+func (s *EquipmentInventory) EquipmentSlot(equipmentID uint64) (uint64, bool) {
+ slot, ok := s.slots[equipmentID]
+ return slot, ok
+}
diff --git a/go/internal/server/domain/inventory/prestige_illustrations.go b/go/internal/server/domain/inventory/prestige_illustrations.go
new file mode 100644
index 0000000..84c8129
--- /dev/null
+++ b/go/internal/server/domain/inventory/prestige_illustrations.go
@@ -0,0 +1,31 @@
+package inventory
+
+func (s *Inventory) AttachPrestigeIllustrations(illustrations map[uint64]uint64) {
+ s.prestigeIllustrations = illustrations
+}
+
+func (s *Inventory) withPrestigeIllustrations(items []Item) []Item {
+ if len(s.prestigeIllustrations) == 0 {
+ return items
+ }
+ seen := make(map[uint64]bool)
+ for _, item := range items {
+ if item.Type == 25 && item.Count != 0 {
+ seen[item.ID] = true
+ }
+ }
+ var attached []Item
+ for _, item := range items {
+ if item.Type != 45 || item.Count == 0 {
+ continue
+ }
+ id := s.prestigeIllustrations[item.ID]
+ if id == 0 || seen[id] {
+ continue
+ }
+ seen[id] = true
+ // Linked illustrations are immutable ownership views, outside mutable item indices.
+ attached = append(attached, Item{InvenIndex: 1<<62 | id, ID: id, Type: 25, Count: 1, TimeValue: item.TimeValue})
+ }
+ return append(items, attached...)
+}
diff --git a/go/internal/server/domain/inventory/protocol_items_adapter.go b/go/internal/server/domain/inventory/protocol_items_adapter.go
index 68d5f25..f1f1fd5 100644
--- a/go/internal/server/domain/inventory/protocol_items_adapter.go
+++ b/go/internal/server/domain/inventory/protocol_items_adapter.go
@@ -72,6 +72,7 @@ func (s *Inventory) Handle(ctx command.Context, path string, request []byte) (in
items := make([]Item, 0, len(s.starter)+len(s.owned.Items))
items = append(items, s.starter...)
items = append(items, s.owned.Items...)
+ items = s.withPrestigeIllustrations(items)
seq, present, err := wire.Varint(request, 1)
if err != nil || !present || seq == 0 {
return 0, nil, true, fmt.Errorf("player: %s invalid sequence", path)
diff --git a/go/internal/server/domain/life/bonuses.go b/go/internal/server/domain/life/bonuses.go
new file mode 100644
index 0000000..8c40d0e
--- /dev/null
+++ b/go/internal/server/domain/life/bonuses.go
@@ -0,0 +1,90 @@
+package life
+
+import (
+ "encoding/binary"
+ "math"
+
+ "bd2server/internal/server/protocol/wire"
+)
+
+func number(b []byte, field int) float64 {
+ var result float64
+ _ = wire.Walk(b, func(f wire.Field) error {
+ if f.Number == field && f.Type == 1 {
+ result = math.Float64frombits(binary.LittleEndian.Uint64(f.Value))
+ }
+ return nil
+ })
+ return result
+}
+func (s *Service) stats(v *snapshot, group uint64) (uint64, uint64, error) {
+ if group < 1 || group > 3 {
+ return 0, 0, ErrInvalid
+ }
+ field := map[uint64]int{1: 23, 2: 27, 3: 13}[group]
+ skill, bonus := float64(num(s.design.Row("LifeDefaultTable", 0), field)), float64(0)
+ add := func(ids []uint64, count uint64) {
+ for _, id := range ids {
+ r := s.design.Row("LifeBuffTable", id)
+ typ := num(r, 4)
+ value := number(r, 5) * float64(count)
+ if typ == group*10+1 {
+ skill += value
+ }
+ if typ == group*10+2 {
+ bonus += value
+ }
+ }
+ }
+ for g := uint64(1); g <= 3; g++ {
+ add(ints(s.design.Row("LifeCharGrowthTable", g, v.Growth[(g-1)*2]), 1), 1)
+ }
+ for g, id := range v.Tools {
+ add(ints(s.design.Row("LifeToolTable", g, id), 2), 1)
+ }
+ for id, count := range v.Counts {
+ if num(s.design.Row("LifeObjectGroupTable", id), 12) == 3 {
+ count = v.ActiveCounts[id]
+ }
+ if count > 0 {
+ add(ints(s.design.Row("LifeObjectGroupTable", id), 2), count)
+ }
+ }
+ for id, until := range v.Foods {
+ if until > s.options.Now().Unix() {
+ add(ints(s.design.Row("LifeItemTable", id), 1), 1)
+ }
+ }
+ if math.IsNaN(skill) || math.IsInf(skill, 0) || skill < 0 || skill > math.MaxInt32 || math.IsNaN(bonus) || math.IsInf(bonus, 0) || bonus < 0 || bonus > math.MaxInt32 {
+ return 0, 0, ErrInvalid
+ }
+ return uint64(skill), uint64(bonus), nil
+}
+func (s *Service) grade(table uint64) (uint64, error) {
+ r := s.design.Row("LifeCropGradeTable", table)
+ grades, weights := ints(r, 1), ints(r, 3)
+ if len(grades) == 0 || len(grades) != len(weights) {
+ return 0, ErrInvalid
+ }
+ var total uint64
+ for _, w := range weights {
+ if w > math.MaxInt32 || total > math.MaxInt32-w {
+ return 0, ErrInvalid
+ }
+ total += w
+ }
+ if total == 0 {
+ return 0, ErrInvalid
+ }
+ pick, err := s.options.Sample(total)
+ if err != nil || pick >= total {
+ return 0, ErrInvalid
+ }
+ for i, w := range weights {
+ if pick < w {
+ return grades[i], nil
+ }
+ pick -= w
+ }
+ return 0, ErrInvalid
+}
diff --git a/go/internal/server/domain/life/economy.go b/go/internal/server/domain/life/economy.go
new file mode 100644
index 0000000..ee5f8aa
--- /dev/null
+++ b/go/internal/server/domain/life/economy.go
@@ -0,0 +1,257 @@
+package life
+
+import (
+ "fmt"
+ "math"
+ "strconv"
+ "time"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/protocol/wire"
+)
+
+func (s *Service) economy(v *snapshot, path string, req []byte) ([]byte, error) {
+ id, count := num(req, 2), num(req, 3)
+ switch path {
+ case "/LifeCrafting":
+ d := s.design.Row("LifeCraftingObjectTable", id)
+ if d == nil || count == 0 || count > math.MaxInt32 {
+ return nil, ErrInvalid
+ }
+ if !s.hasFunction(v, 11) {
+ return nil, ErrInvalid
+ }
+ cost, err := costs(d, 5, 4, 3, count)
+ if err != nil {
+ return nil, err
+ }
+ if err = s.spend(v, cost); err != nil {
+ return nil, err
+ }
+ bundle, err := s.grant(v, []gamedata.Reward{{Type: 65, ID: id, Count: count}})
+ return wire.AppendBytes(nil, 1, bundle), err
+ case "/LifeCooking":
+ d := s.design.Row("LifeCookTable", id)
+ if d == nil || count == 0 || count > math.MaxInt32 || !s.hasFunction(v, 13) {
+ return nil, ErrInvalid
+ }
+ unique, quantity := ints(d, 3), ints(d, 2)
+ if len(unique) != len(quantity) {
+ return nil, ErrInvalid
+ }
+ required := map[uint64]uint64{}
+ for i, u := range unique {
+ if quantity[i] > math.MaxInt32/count {
+ return nil, ErrInvalid
+ }
+ required[u] += quantity[i] * count
+ }
+ cost, err := s.uniqueCosts(v, required, messages(req, 4))
+ if err != nil {
+ return nil, err
+ }
+ if err = s.spend(v, cost); err != nil {
+ return nil, err
+ }
+ bundle, err := s.grant(v, []gamedata.Reward{{Type: 66, ID: num(d, 4), Count: count}})
+ return wire.AppendBytes(nil, 1, bundle), err
+ case "/LifeToolUpgrade":
+ group := id
+ current, ok := v.Tools[group]
+ if !ok || !s.hasFunction(v, 14) {
+ return nil, ErrInvalid
+ }
+ ids := s.design.ToolGroups[group]
+ var next uint64
+ for i, x := range ids {
+ if x == current && i+1 < len(ids) {
+ next = ids[i+1]
+ }
+ }
+ d := s.design.Row("LifeToolTable", group, next)
+ if d == nil || next == 0 {
+ return nil, ErrInvalid
+ }
+ cost, err := costs(d, 15, 14, 13, 1)
+ if err != nil {
+ return nil, err
+ }
+ if price := num(d, 16); price > 0 {
+ cost = append(cost, gamedata.Reward{Type: 64, Count: price})
+ }
+ if err = s.spend(v, cost); err != nil {
+ return nil, err
+ }
+ v.Tools[group] = next
+ return row(1, group, 2, next), nil
+ case "/LifeEatFood":
+ used := messages(req, 2)
+ if len(used) != 1 {
+ return nil, ErrInvalid
+ }
+ it := used[0]
+ id = num(it, 2)
+ if num(it, 3) != 66 || num(it, 4) != 1 {
+ return nil, ErrInvalid
+ }
+ d := s.design.Row("LifeItemTable", id)
+ duration := uint64(0)
+ for _, buff := range ints(d, 1) {
+ duration = max(duration, num(s.design.Row("LifeBuffTable", buff), 1))
+ }
+ if duration == 0 {
+ return nil, ErrInvalid
+ }
+ if err := s.spend(v, []gamedata.Reward{{Type: 66, ID: id, Count: 1}}); err != nil {
+ return nil, err
+ }
+ v.Foods[id] = s.options.Now().Unix() + int64(duration)
+ return wire.AppendBytes(nil, 1, row(1, id, 2, uint64(v.Foods[id]))), nil
+ case "/LifeShopBuy":
+ return s.buy(v, req)
+ case "/LifeShopSell":
+ lines := messages(req, 2)
+ if len(lines) == 0 || len(lines) > 128 {
+ return nil, ErrInvalid
+ }
+ var cost, gain []gamedata.Reward
+ for _, line := range lines {
+ group, id, count := num(line, 2), num(line, 3), num(line, 4)
+ d := s.design.Row("LifeSellItemTable", group, id)
+ if d == nil || count == 0 || count > math.MaxInt32 {
+ return nil, ErrInvalid
+ }
+ amount, price := num(d, 3), num(d, 6)
+ if amount == 0 || amount > math.MaxInt32/count || price > math.MaxInt32/count {
+ return nil, ErrInvalid
+ }
+ it := v.Items[itemKey(num(d, 5), num(d, 4))]
+ if num(line, 1) != it.Index {
+ return nil, ErrInvalid
+ }
+ cost = append(cost, gamedata.Reward{Type: num(d, 5), ID: num(d, 4), Count: amount * count})
+ if price > 0 {
+ gain = append(gain, gamedata.Reward{Type: num(d, 8), ID: num(d, 7), Count: price * count})
+ }
+ }
+ if err := s.spend(v, cost); err != nil {
+ return nil, err
+ }
+ bundle, err := s.grant(v, gain)
+ return wire.AppendBytes(nil, 1, bundle), err
+ }
+ return nil, ErrInvalid
+}
+func (s *Service) hasFunction(v *snapshot, function uint64) bool {
+ for id, count := range v.ActiveCounts {
+ if count > 0 && num(s.design.Row("LifeBuildingObjectTable", id), 2) == function {
+ return true
+ }
+ }
+ return false
+}
+func (s *Service) uniqueCosts(v *snapshot, required map[uint64]uint64, selected [][]byte) ([]gamedata.Reward, error) {
+ var cost []gamedata.Reward
+ for _, raw := range selected {
+ typ, id, count := num(raw, 3), num(raw, 2), num(raw, 4)
+ d := s.design.Row("LifeItemTable", id)
+ unique := num(d, 10)
+ if typ != 66 || d == nil || count == 0 || count > required[unique] {
+ return nil, ErrInvalid
+ }
+ it := v.Items[itemKey(typ, id)]
+ if num(raw, 1) != it.Index {
+ return nil, ErrInvalid
+ }
+ required[unique] -= count
+ cost = append(cost, gamedata.Reward{Type: typ, ID: id, Count: count})
+ }
+ for _, n := range required {
+ if n != 0 {
+ return nil, ErrInvalid
+ }
+ }
+ return cost, nil
+}
+func (s *Service) period(kind uint64) string {
+ now := s.options.Now().UTC()
+ switch kind {
+ case 0, 4:
+ return "all"
+ case 1:
+ return now.Format("2006-01-02")
+ case 2:
+ y, w := now.ISOWeek()
+ return fmt.Sprintf("%d-%d", y, w)
+ case 3:
+ return now.Format("2006-01")
+ }
+ return "invalid"
+}
+func (s *Service) buy(v *snapshot, req []byte) ([]byte, error) {
+ group, id, count := num(req, 2), num(req, 3), num(req, 4)
+ d := s.design.Row("LifeBuyItemTable", group, id)
+ if d == nil || count == 0 || count > math.MaxInt32 {
+ return nil, ErrInvalid
+ }
+ quantity, price := num(d, 3), num(d, 6)
+ if quantity == 0 || quantity > math.MaxInt32/count || price > math.MaxInt32/count {
+ return nil, ErrInvalid
+ }
+ key := itemKey(group, id)
+ p := v.Purchases[key]
+ period := s.period(num(d, 10))
+ if period == "invalid" {
+ return nil, ErrInvalid
+ }
+ if p.Period != period {
+ p = purchase{Period: period}
+ }
+ limit := num(d, 9)
+ if limit > 0 && (p.Count >= limit || count > limit-p.Count) {
+ return nil, ErrInvalid
+ }
+ if price > 0 {
+ if err := s.spend(v, []gamedata.Reward{{Type: num(d, 8), ID: num(d, 7), Count: price * count}}); err != nil {
+ return nil, err
+ }
+ }
+ bundle, err := s.grant(v, []gamedata.Reward{{Type: num(d, 5), ID: num(d, 4), Count: quantity * count}})
+ if err != nil {
+ return nil, err
+ }
+ p.Count += count
+ v.Purchases[key] = p
+ return wire.AppendBytes(nil, 1, bundle), nil
+}
+func (s *Service) shopInfo(v *snapshot) []byte {
+ now := s.options.Now().UTC()
+ day := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, time.UTC)
+ days := (8 - int(now.Weekday())) % 7
+ if days == 0 {
+ days = 7
+ }
+ week := time.Date(now.Year(), now.Month(), now.Day()+days, 0, 0, 0, 0, time.UTC)
+ month := time.Date(now.Year(), now.Month()+1, 1, 0, 0, 0, 0, time.UTC)
+ b := row(2, uint64(day.Unix()), 3, uint64(week.Unix()), 4, uint64(month.Unix()))
+ for key, p := range v.Purchases {
+ var group, id uint64
+ if _, err := fmt.Sscanf(key, "%d:%d", &group, &id); err != nil {
+ continue
+ }
+ d := s.design.Row("LifeBuyItemTable", group, id)
+ if d != nil && p.Period == s.period(num(d, 10)) {
+ b = wire.AppendBytes(b, 1, row(1, group, 2, id, 3, p.Count))
+ }
+ }
+ return b
+}
+
+func (s *Service) uniqueItem(unique, grade uint64) (uint64, error) {
+ for _, r := range s.design.ItemsByUnique[unique] {
+ if num(r, 3) == grade {
+ return num(r, 5), nil
+ }
+ }
+ return 0, fmt.Errorf("life: missing unique item %s", strconv.FormatUint(unique, 10))
+}
diff --git a/go/internal/server/domain/life/gameplay_integration_test.go b/go/internal/server/domain/life/gameplay_integration_test.go
new file mode 100644
index 0000000..85b57ff
--- /dev/null
+++ b/go/internal/server/domain/life/gameplay_integration_test.go
@@ -0,0 +1,254 @@
+//go:build integration
+
+package life_test
+
+import (
+ "bytes"
+ "context"
+ "encoding/binary"
+ "fmt"
+ "path/filepath"
+ "sort"
+ "testing"
+ "time"
+
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/life"
+ "bd2server/internal/server/protocol/wire"
+ accountstate "bd2server/internal/server/storage/account"
+)
+
+// LifePacket consumes server DB records for residents/helper slots; its
+// PackInfoLife UI promises BaseLogging per HelperWorkBaseTime and caps accrual
+// at MaxRewardTime. This exercises that contract through actual GameData,
+// separate committed SQLite commands and a reopened repository.
+func TestCurrentLifeGatherBuildRecruitSettleAndRelog(t *testing.T) {
+ versions, err := versionconfig.Find()
+ if err != nil {
+ t.Fatal(err)
+ }
+ d, err := gamedata.LoadLifeCatalog(versions.Resolve("data/resources/GameData"), versions.GameDataVersion)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dbPath := filepath.Join(t.TempDir(), "state.db")
+ repo, err := accountstate.Open(dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer func() {
+ if err := repo.Close(); err != nil {
+ t.Error(err)
+ }
+ }()
+ now := time.Date(2026, 10, 17, 8, 0, 0, 0, time.UTC)
+ session := "initial-login"
+ sequence := uint64(0)
+ options := life.Options{Now: func() time.Time { return now }, Sample: func(uint64) (uint64, error) { return 0, nil }, ValidateAvatar: func(command.Context, []byte) error { return nil }}
+ run := func(fn func(command.Context, *life.Service) error) {
+ t.Helper()
+ tx, err := repo.BeginCommand(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer tx.Rollback()
+ ctx := command.Context{Identity: command.Identity{AccountID: "life-test", SessionID: session}, State: tx}
+ if existing, err := tx.Load("missions"); err != nil {
+ t.Fatal(err)
+ } else if existing == nil {
+ if err := tx.Save("missions", []byte("{}")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ s, err := life.Open(ctx, d, options)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := fn(ctx, s); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatal(err)
+ }
+ }
+ call := func(path string, request []byte) []byte {
+ t.Helper()
+ sequence++
+ var body []byte
+ run(func(ctx command.Context, s *life.Service) error {
+ _, out, handled, err := s.Handle(ctx, path, append(proto(1, sequence), request...))
+ if !handled {
+ t.Fatalf("unhandled %s", path)
+ }
+ body = out
+ if err != nil {
+ return fmt.Errorf("%s: %w", path, err)
+ }
+ return nil
+ })
+ return body
+ }
+ worlds := make([]uint64, 0, len(d.Tables["LifeWorldTable"]))
+ for key := range d.Tables["LifeWorldTable"] {
+ worlds = append(worlds, key[0])
+ }
+ sort.Slice(worlds, func(i, j int) bool { return worlds[i] < worlds[j] })
+ if len(worlds) < 2 {
+ t.Fatal("terrain choice requires at least two current design worlds")
+ }
+ call("/LifeUserInfo", nil)
+ call("/LifeWorldChoice", proto(2, worlds[0]))
+ initial := call("/LifeInfo", nil)
+ var forestPlace, forestObject []byte
+ var chunk uint64
+ for _, place := range repeated(t, initial, 1) {
+ if chunk == 0 {
+ chunk = scalar(t, place, 1)
+ }
+ for _, o := range repeated(t, place, 2) {
+ bd := d.Row("LifeBuildingObjectTable", scalar(t, o, 6))
+ if scalar(t, bd, 2) == 1 && len(repeated(t, o, 10)) > 0 {
+ forestPlace, forestObject = place, o
+ break
+ }
+ }
+ if forestObject != nil {
+ break
+ }
+ }
+ if forestObject == nil {
+ t.Fatal("current terrain has no logging resource to play")
+ }
+ inner := repeated(t, forestObject, 10)[0]
+ gatherReq := child(nil, 2, child(proto(1, scalar(t, forestPlace, 1)), 2, child(proto(1, scalar(t, forestObject, 1), 2, scalar(t, forestObject, 2), 6, scalar(t, forestObject, 6)), 10, proto(4, scalar(t, inner, 4), 6, scalar(t, inner, 6)))))
+ harvest := call("/LifeWorldObjectGathering", gatherReq)
+ if len(repeated(t, nested(t, harvest, 2), 1)) == 0 {
+ t.Fatal("actual logging yielded no materials")
+ }
+ earned := nested(t, harvest, 1)
+ build := func(function, x uint64) []byte {
+ t.Helper()
+ var id uint64
+ for key, r := range d.Tables["LifeBuildingObjectTable"] {
+ group := d.Row("LifeObjectGroupTable", key[0])
+ if scalar(t, r, 2) == function && scalar(t, group, 7) != 0 && scalar(t, group, 13) <= 1 && (id == 0 || key[0] < id) {
+ id = key[0]
+ }
+ }
+ if id == 0 {
+ t.Fatalf("missing initial building function %d", function)
+ }
+ bd := d.Row("LifeBuildingObjectTable", id)
+ types, ids, counts := plainInts(t, bd, 10), plainInts(t, bd, 9), plainInts(t, bd, 8)
+ var funding []gamedata.Reward
+ for i, typ := range types {
+ funding = append(funding, gamedata.Reward{Type: typ, ID: ids[i], Count: counts[i]})
+ }
+ run(func(ctx command.Context, s *life.Service) error {
+ _, err := s.Apply(ctx, "building-budget-"+string(rune(function)), nil, funding)
+ return err
+ })
+ p := child(proto(1, chunk), 2, proto(6, id, 1, x, 2, 1))
+ placed := nested(t, call("/LifeWorldObjectPlaceSave", child(nil, 2, p)), 1)
+ if scalar(t, nested(t, placed, 2), 7) == 0 {
+ now = now.Add(time.Duration(scalar(t, bd, 11)) * time.Second)
+ placed = nested(t, call("/LifeWorldObjectBuildCompleted", child(nil, 2, p)), 1)
+ }
+ return placed
+ }
+ residentHouse, workerHouse := build(102, 1), build(101, 2)
+ candidates := repeated(t, call("/LifeHelperGacha", child(nil, 2, workerHouse)), 1)
+ if len(candidates) == 0 {
+ t.Fatal("worker recruitment offered no candidates")
+ }
+ candidate := candidates[0]
+ avatar := nested(t, candidate, 5)
+ resident := nested(t, call("/LifeCitizenRecruit", child(child(nil, 2, residentHouse), 3, child(nil, 3, avatar))), 1)
+ defaults := d.Row("LifeDefaultTable", 0)
+ hirePrice := scalar(t, defaults, 19)
+ run(func(ctx command.Context, s *life.Service) error {
+ _, err := s.Apply(ctx, "hire-budget", nil, []gamedata.Reward{{Type: 64, Count: hirePrice}})
+ return err
+ })
+ call("/LifeHelperRecruit", child(child(nil, 3, candidate), 4, workerHouse))
+ assigned := proto(1, scalar(t, candidate, 1), 6, 1)
+ call("/LifeHelperAssign", child(child(nil, 2, assigned), 3, workerHouse))
+ period := scalar(t, defaults, 20)
+ now = now.Add(time.Duration(period) * time.Second)
+ preview := call("/LifeHelperRewardInfo", nil)
+ total := uint64(0)
+ for _, it := range repeated(t, nested(t, preview, 2), 1) {
+ total += scalar(t, it, 4)
+ }
+ species := d.Row("LifeHelperSpeciesTable", scalar(t, candidate, 2))
+ if total != scalar(t, species, 3) {
+ t.Fatalf("one logging cycle promised %d items, previewed %d", scalar(t, species, 3), total)
+ }
+ claim := call("/LifeHelperReward", nil)
+ if len(repeated(t, nested(t, claim, 1), 1)) == 0 {
+ t.Fatal("settlement yielded no persisted materials")
+ }
+ profileBefore := call("/LifeUserInfo", nil)
+ itemsBefore := call("/LifeInfo", nil)
+ if err := repo.Close(); err != nil {
+ t.Fatal(err)
+ }
+ repo, err = accountstate.Open(dbPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ session = "relogin"
+ restored := call("/LifeUserInfo", nil)
+ if !bytes.Equal(profileBefore, restored) || !bytes.Equal(nested(t, restored, 3), resident) {
+ t.Fatal("reopened account lost resident/helper/user records")
+ }
+ if !bytes.Equal(nested(t, nested(t, restored, 2), 3), earned) {
+ t.Fatal("reopened account lost earned growth")
+ }
+ if !bytes.Equal(itemsBefore, call("/LifeInfo", nil)) {
+ t.Fatal("reopened account lost placements/inventory")
+ }
+ run(func(ctx command.Context, s *life.Service) error {
+ coin, err := s.Coin(ctx)
+ if err == nil && coin != 0 {
+ t.Fatalf("hire debit not conserved across database reopen: %d", coin)
+ }
+ return err
+ })
+ secondPreview := call("/LifeHelperRewardInfo", nil)
+ if len(repeated(t, nested(t, secondPreview, 2), 1)) != 0 {
+ t.Fatal("relogin reclaimed the same helper interval")
+ }
+}
+
+func plainInts(t *testing.T, b []byte, field int) []uint64 {
+ t.Helper()
+ var out []uint64
+ for _, f := range extractFields(t, b) {
+ if f.Number == field {
+ if f.Type == 0 {
+ out = append(out, scalar(t, b, field))
+ } else if f.Type == 2 {
+ for raw := f.Value; len(raw) > 0; {
+ v, n := binary.Uvarint(raw)
+ if n <= 0 {
+ t.Fatal("bad packed rule")
+ }
+ out = append(out, v)
+ raw = raw[n:]
+ }
+ }
+ }
+ }
+ return out
+}
+func extractFields(t *testing.T, b []byte) []wire.Field {
+ t.Helper()
+ var out []wire.Field
+ if err := wire.Walk(b, func(f wire.Field) error { out = append(out, f); return nil }); err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
diff --git a/go/internal/server/domain/life/helpers.go b/go/internal/server/domain/life/helpers.go
new file mode 100644
index 0000000..29f9de7
--- /dev/null
+++ b/go/internal/server/domain/life/helpers.go
@@ -0,0 +1,388 @@
+package life
+
+import (
+ "fmt"
+ "math"
+ "slices"
+ "strings"
+ "unicode/utf8"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+)
+
+func (s *Service) citizen(ctx command.Context, v *snapshot, path string, req []byte) ([]byte, error) {
+ _, o, err := s.selected(v, msg(req, 2))
+ if err != nil {
+ return nil, err
+ }
+ if o.Status != 1 || num(s.design.Row("LifeBuildingObjectTable", o.ID), 2) != 102 {
+ return nil, ErrInvalid
+ }
+ avatar := msg(msg(req, 3), 3)
+ if len(avatar) == 0 || num(avatar, 1) == 0 || s.options.ValidateAvatar == nil {
+ return nil, ErrInvalid
+ }
+ if err := s.options.ValidateAvatar(ctx, avatar); err != nil {
+ return nil, err
+ }
+ c, exists := v.Citizens[o.Index]
+ if path == "/LifeCitizenRecruit" {
+ if exists {
+ return nil, ErrInvalid
+ }
+ c = citizen{Index: v.Next, Slot: o.Index}
+ v.Next++
+ } else if !exists {
+ return nil, ErrInvalid
+ }
+ c.Avatar = append([]byte(nil), avatar...)
+ v.Citizens[o.Index] = c
+ return wire.AppendBytes(nil, 1, citizenWire(c)), nil
+}
+func (s *Service) building(v *snapshot, raw []byte) (*object, error) {
+ _, o, err := s.selected(v, raw)
+ if err != nil {
+ return nil, err
+ }
+ if o.Status != 1 || num(s.design.Row("LifeBuildingObjectTable", o.ID), 2) != 101 {
+ return nil, ErrInvalid
+ }
+ return o, nil
+}
+func (s *Service) chooseSpecies() (helper, error) {
+ rows := s.design.Tables["LifeHelperSpeciesTable"]
+ ids := make([]uint64, 0, len(rows))
+ var total uint64
+ for key, r := range rows {
+ ids = append(ids, key[0])
+ total += num(r, 10)
+ }
+ slices.Sort(ids)
+ if total == 0 {
+ return helper{}, ErrInvalid
+ }
+ pick, err := s.options.Sample(total)
+ if err != nil || pick >= total {
+ return helper{}, ErrInvalid
+ }
+ var d []byte
+ for _, id := range ids {
+ r := s.design.Row("LifeHelperSpeciesTable", id)
+ w := num(r, 10)
+ if pick < w {
+ d = r
+ break
+ }
+ pick -= w
+ }
+ if d == nil {
+ return helper{}, ErrInvalid
+ }
+ avatar := row(1, num(d, 1), 3, num(d, 7), 6, num(d, 5))
+ for _, field := range []struct{ design, proto int }{{6, 2}, {8, 5}} {
+ values := ints(d, field.design)
+ if len(values) == 0 {
+ continue
+ }
+ n, err := s.options.Sample(uint64(len(values)))
+ if err != nil || n >= uint64(len(values)) {
+ return helper{}, ErrInvalid
+ }
+ avatar = wire.AppendVarint(avatar, field.proto, values[n])
+ }
+ return helper{ID: num(d, 9), Avatar: avatar}, nil
+}
+func (s *Service) helpers(v *snapshot, path string, req []byte) ([]byte, error) {
+ if path == "/LifeHelperReward" {
+ return s.settle(v, true)
+ }
+ placeField := 3
+ if path == "/LifeHelperGacha" || path == "/LifeHelperGachaDelete" {
+ placeField = 2
+ }
+ if path == "/LifeHelperRecruit" {
+ placeField = 4
+ }
+ o, err := s.building(v, msg(req, placeField))
+ if err != nil {
+ return nil, err
+ }
+ if path == "/LifeHelperGachaDelete" {
+ if len(v.Candidates[o.Index]) == 0 {
+ return nil, ErrInvalid
+ }
+ delete(v.Candidates, o.Index)
+ return nil, nil
+ }
+ if path == "/LifeHelperGacha" {
+ if len(v.Candidates[o.Index]) > 0 {
+ var b []byte
+ for _, h := range v.Candidates[o.Index] {
+ b = wire.AppendBytes(b, 1, helperWire(h))
+ }
+ return b, nil
+ }
+ count := num(s.design.Row("LifeDefaultTable", 0), 18)
+ if count == 0 || count > 32 {
+ return nil, ErrInvalid
+ }
+ var b []byte
+ for range count {
+ h, err := s.chooseSpecies()
+ if err != nil {
+ return nil, err
+ }
+ h.Index = v.Next
+ v.Next++
+ h.Slot = o.Index
+ v.Candidates[o.Index] = append(v.Candidates[o.Index], h)
+ b = wire.AppendBytes(b, 1, helperWire(h))
+ }
+ return b, nil
+ }
+ input := msg(req, 2)
+ if path == "/LifeHelperRecruit" {
+ input = msg(req, 3)
+ }
+ id := num(input, 1)
+ if path == "/LifeHelperRecruit" {
+ var selected *helper
+ for _, candidate := range v.Candidates[o.Index] {
+ if candidate.Index == id {
+ h := candidate
+ selected = &h
+ }
+ }
+ if selected == nil {
+ return nil, ErrInvalid
+ }
+ occupied := uint64(0)
+ for index, h := range v.Helpers {
+ if h.Slot == o.Index {
+ occupied = index
+ }
+ }
+ if (occupied != 0) != (num(req, 2) != 0) {
+ return nil, ErrInvalid
+ }
+ price := num(s.design.Row("LifeDefaultTable", 0), 19)
+ if price > 0 {
+ if err := s.spend(v, []gamedata.Reward{{Type: 64, Count: price}}); err != nil {
+ return nil, err
+ }
+ }
+ settled, err := s.settle(v, false)
+ if err != nil {
+ return nil, err
+ }
+ var b []byte
+ if occupied != 0 {
+ old := v.Helpers[occupied]
+ old.Slot = 0
+ old.Work = 0
+ old.WorkID = 0
+ old.Assigned = 0
+ v.Helpers[occupied] = old
+ b = wire.AppendBytes(b, 1, helperWire(old))
+ }
+ v.Helpers[id] = *selected
+ delete(v.Candidates, o.Index)
+ b = appendConnectedHelpers(b, 1, v)
+ return wire.AppendBytes(b, 2, settled), nil
+ }
+ h, found := v.Helpers[id]
+ if !found {
+ return nil, ErrInvalid
+ }
+ if path != "/LifeHelperReconnect" && h.Slot != o.Index {
+ return nil, ErrInvalid
+ }
+ switch path {
+ case "/LifeHelperFire":
+ bundle, err := s.settle(v, false)
+ if err != nil {
+ return nil, err
+ }
+ delete(v.Helpers, id)
+ return appendConnectedHelpers(wire.AppendBytes(nil, 1, bundle), 2, v), nil
+ case "/LifeHelperReName":
+ name := string(msg(input, 4))
+ if !utf8.ValidString(name) || utf8.RuneCountInString(name) > 24 || strings.TrimSpace(name) == "" {
+ return nil, ErrInvalid
+ }
+ h.Name = name
+ v.Helpers[id] = h
+ return nil, nil
+ case "/LifeHelperReconnect":
+ if h.Slot != 0 {
+ return nil, ErrInvalid
+ }
+ for _, other := range v.Helpers {
+ if other.Slot == o.Index {
+ return nil, ErrInvalid
+ }
+ }
+ h.Slot = o.Index
+ h.Work = 0
+ h.WorkID = 0
+ h.Assigned = 0
+ v.Helpers[id] = h
+ return nil, nil
+ case "/LifeHelperAssign":
+ work, workID := num(input, 6), num(input, 7)
+ if work > 3 || work < 3 && workID != 0 || work == 3 && s.design.Row("LifeCropSeedTable", workID) == nil {
+ return nil, ErrInvalid
+ }
+ bundle, err := s.settle(v, false)
+ if err != nil {
+ return nil, err
+ }
+ h = v.Helpers[id]
+ h.Work, h.WorkID = work, workID
+ if work > 0 {
+ h.Assigned = s.options.Now().Unix()
+ } else {
+ h.Assigned = 0
+ }
+ v.Helpers[id] = h
+ return wire.AppendBytes(appendConnectedHelpers(nil, 1, v), 2, bundle), nil
+ }
+ return nil, ErrInvalid
+}
+
+func appendConnectedHelpers(b []byte, field int, v *snapshot) []byte {
+ for _, id := range sorted(v.Helpers) {
+ if h := v.Helpers[id]; h.Slot != 0 {
+ b = wire.AppendBytes(b, field, helperWire(h))
+ }
+ }
+ return b
+}
+
+func (s *Service) helperRewards(v *snapshot) ([]gamedata.Reward, map[uint64]int64, int64, error) {
+ var gains []gamedata.Reward
+ progress := map[uint64]int64{}
+ earliest := int64(0)
+ now := s.options.Now().Unix()
+ defaults := s.design.Row("LifeDefaultTable", 0)
+ maxTime := int64(num(defaults, 26))
+ for _, id := range sorted(v.Helpers) {
+ h := v.Helpers[id]
+ if h.Slot == 0 || h.Work == 0 || h.Assigned == 0 {
+ continue
+ }
+ if earliest == 0 || h.Assigned < earliest {
+ earliest = h.Assigned
+ }
+ d := s.design.Row("LifeHelperSpeciesTable", h.ID)
+ period := int64(num(defaults, 20))
+ statField := map[uint64]int{1: 3, 2: 4, 3: 2}[h.Work]
+ if statField == 0 {
+ return nil, nil, 0, ErrInvalid
+ }
+ quantity := num(d, statField)
+ var unique []uint64
+ if h.Work == 3 {
+ crop := s.design.Row("LifeCropSeedTable", h.WorkID)
+ period = int64(num(crop, 1))
+ unique = []uint64{num(crop, 3)}
+ } else {
+ unique = s.design.HelperUniques[h.Work]
+ }
+ if period <= 0 || maxTime <= 0 || quantity == 0 {
+ return nil, nil, 0, ErrInvalid
+ }
+ elapsed := min(max(now-h.Assigned, 0), maxTime)
+ cycles := uint64(elapsed / period)
+ if cycles == 0 {
+ continue
+ }
+ if quantity > math.MaxInt32/cycles {
+ return nil, nil, 0, ErrInvalid
+ }
+ quantity *= cycles
+ if len(unique) == 0 {
+ return nil, nil, 0, fmt.Errorf("life: helper has no reward pool")
+ }
+ for i, u := range unique {
+ count := quantity / uint64(len(unique))
+ if uint64(i) < quantity%uint64(len(unique)) {
+ count++
+ }
+ if count == 0 {
+ continue
+ }
+ grade := uint64(0)
+ if h.Work == 3 {
+ var err error
+ grade, err = s.grade(num(defaults, 17))
+ if err != nil {
+ return nil, nil, 0, err
+ }
+ }
+ var itemID uint64
+ var err error
+ if h.Work == 3 {
+ itemID, err = s.uniqueItem(u, grade)
+ } else {
+ rows := s.design.ItemsByUnique[u]
+ if len(rows) == 0 {
+ return nil, nil, 0, ErrInvalid
+ }
+ itemID = num(rows[0], 5)
+ }
+ if err != nil {
+ return nil, nil, 0, err
+ }
+ gains = append(gains, gamedata.Reward{Type: 66, ID: itemID, Count: count})
+ }
+ progress[id] = h.Assigned + int64(cycles)*period
+ if now-h.Assigned >= maxTime {
+ progress[id] = now
+ }
+ }
+ return gains, progress, earliest, nil
+}
+func rewardPreview(gains []gamedata.Reward) []byte {
+ var b []byte
+ counts := map[uint64]uint64{}
+ for _, r := range gains {
+ counts[r.ID] += r.Count
+ }
+ for _, id := range sorted(counts) {
+ b = wire.AppendBytes(b, 1, itemWire(item{ID: id, Type: 66, Count: counts[id]}))
+ }
+ return b
+}
+func (s *Service) helperPreview(v *snapshot) ([]byte, error) {
+ gains, _, earliest, err := s.helperRewards(v)
+ if err != nil {
+ return nil, err
+ }
+ return wire.AppendBytes(row(1, uint64(earliest)), 2, rewardPreview(gains)), nil
+}
+func (s *Service) settle(v *snapshot, response bool) ([]byte, error) {
+ gains, progress, _, err := s.helperRewards(v)
+ if err != nil {
+ return nil, err
+ }
+ bundle, err := s.grant(v, gains)
+ if err != nil {
+ return nil, err
+ }
+ for id, at := range progress {
+ h := v.Helpers[id]
+ h.Assigned = at
+ v.Helpers[id] = h
+ }
+ if !response {
+ return bundle, nil
+ }
+ b := wire.AppendBytes(nil, 1, bundle)
+ for _, id := range sorted(v.Helpers) {
+ b = wire.AppendBytes(b, 2, helperWire(v.Helpers[id]))
+ }
+ return b, nil
+}
diff --git a/go/internal/server/domain/life/life.go b/go/internal/server/domain/life/life.go
new file mode 100644
index 0000000..f557e69
--- /dev/null
+++ b/go/internal/server/domain/life/life.go
@@ -0,0 +1,506 @@
+package life
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math"
+ "slices"
+ "sort"
+ "strconv"
+ "time"
+
+ "bd2server/internal/common/util"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+var ErrInvalid = errors.New("life: invalid operation")
+var ErrFunds = errors.New("life: insufficient materials")
+
+type Options struct {
+ Now func() time.Time
+ Sample func(uint64) (uint64, error)
+ ValidateAvatar func(command.Context, []byte) error
+}
+type Service struct {
+ design *gamedata.LifeCatalog
+ options Options
+}
+type item struct{ Index, ID, Type, Count uint64 }
+type object struct {
+ X, Y int32
+ Rotate, Index, ID, Status uint64
+ Start, End int64
+ Inner map[uint64]*object
+ Refund []gamedata.Reward
+}
+type citizen struct {
+ Index, Slot uint64
+ Avatar []byte
+}
+type helper struct {
+ Index, ID, Slot uint64
+ Name string
+ Avatar []byte
+ Work, WorkID uint64
+ Assigned int64
+}
+type purchase struct {
+ Count uint64
+ Period string
+}
+type snapshot struct {
+ Version int
+ World, Coin, Next uint64
+ Growth [6]uint64
+ Chunks map[uint64]bool
+ Objects map[uint64]map[string]*object
+ Counts map[uint64]uint64
+ ActiveCounts map[uint64]uint64
+ Layers map[uint64]uint64
+ Items map[string]item
+ Tools map[uint64]uint64
+ Citizens map[uint64]citizen
+ Helpers map[uint64]helper
+ Candidates map[uint64][]helper
+ Purchases map[string]purchase
+ Foods map[uint64]int64
+ Collections map[uint64]bool
+ ExpansionRefund []gamedata.Reward
+}
+type receipt struct {
+ Request, Body []byte
+ Sequence uint64
+}
+
+func Open(ctx command.Context, design *gamedata.LifeCatalog, options Options) (*Service, error) {
+ if ctx.State == nil || design == nil || design.Row("LifeDefaultTable", 0) == nil {
+ return nil, fmt.Errorf("life: incomplete dependencies")
+ }
+ if options.Now == nil {
+ options.Now = time.Now
+ }
+ if options.Sample == nil {
+ options.Sample = util.RandomUint64N
+ }
+ s := &Service{design: design, options: options}
+ _, err := s.load(ctx)
+ return s, err
+}
+func (s *Service) load(ctx command.Context) (*snapshot, error) {
+ if ctx.State == nil {
+ return nil, ErrInvalid
+ }
+ raw, found, err := ctx.State.LoadEntry("missions", "life_state", "core")
+ if err != nil {
+ return nil, err
+ }
+ if found {
+ var v snapshot
+ if err := json.Unmarshal(raw, &v); err != nil {
+ return nil, err
+ }
+ if v.Version != 1 || v.Next == 0 || v.Chunks == nil || v.Objects == nil || v.Items == nil || v.Citizens == nil || v.Helpers == nil || v.Candidates == nil || v.Tools == nil || v.Counts == nil || v.ActiveCounts == nil || v.Layers == nil || v.Purchases == nil || v.Foods == nil || v.Collections == nil {
+ return nil, fmt.Errorf("life: invalid saved state")
+ }
+ if v.World != 0 && s.design.Row("LifeWorldTable", v.World) == nil {
+ return nil, fmt.Errorf("life: saved world missing in design")
+ }
+ return &v, nil
+ }
+ v := &snapshot{Version: 1, Next: 1, Growth: [6]uint64{1, 0, 1, 0, 1, 0}, Chunks: map[uint64]bool{}, Objects: map[uint64]map[string]*object{}, Counts: map[uint64]uint64{}, ActiveCounts: map[uint64]uint64{}, Layers: map[uint64]uint64{}, Items: map[string]item{}, Tools: map[uint64]uint64{}, Citizens: map[uint64]citizen{}, Helpers: map[uint64]helper{}, Candidates: map[uint64][]helper{}, Purchases: map[string]purchase{}, Foods: map[uint64]int64{}, Collections: map[uint64]bool{}}
+ for group, ids := range s.design.ToolGroups {
+ if len(ids) > 0 {
+ v.Tools[group] = ids[0]
+ }
+ }
+ return v, nil
+}
+func save(ctx command.Context, v *snapshot, changes ...stateio.EntryMutation) error {
+ raw, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+ changes = append(changes, stateio.EntryMutation{Bucket: "life_state", Key: "core", Payload: raw})
+ return ctx.State.SaveWithEntries("missions", nil, changes)
+}
+func num(raw []byte, n int) uint64 { v, _, _ := wire.Varint(raw, n); return v }
+func msg(raw []byte, n int) []byte { v, _, _ := wire.Bytes(raw, n); return v }
+func messages(raw []byte, n int) (out [][]byte) {
+ _ = wire.Walk(raw, func(f wire.Field) error {
+ if f.Number == n && f.Type == 2 {
+ out = append(out, f.Value)
+ }
+ return nil
+ })
+ return
+}
+func ints(raw []byte, n int) (out []uint64) {
+ _ = wire.Walk(raw, func(f wire.Field) error {
+ if f.Number != n {
+ return nil
+ }
+ if f.Type == 0 {
+ v, _ := binary.Uvarint(f.Value)
+ out = append(out, v)
+ }
+ if f.Type == 2 {
+ for b := f.Value; len(b) > 0; {
+ v, k := binary.Uvarint(b)
+ if k <= 0 {
+ break
+ }
+ out = append(out, v)
+ b = b[k:]
+ }
+ }
+ return nil
+ })
+ return
+}
+func row(fields ...uint64) []byte {
+ var b []byte
+ for i := 0; i < len(fields); i += 2 {
+ b = wire.AppendVarint(b, int(fields[i]), fields[i+1])
+ }
+ return b
+}
+func itemKey(typ, id uint64) string {
+ return strconv.FormatUint(typ, 10) + ":" + strconv.FormatUint(id, 10)
+}
+func objectKey(o *object) string { return fmt.Sprintf("%d:%d:%d", o.ID, o.X, o.Y) }
+func sorted[V any](m map[uint64]V) []uint64 {
+ ids := make([]uint64, 0, len(m))
+ for id := range m {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ return ids
+}
+func objectWire(o *object) []byte {
+ b := row(1, uint64(int64(o.X)), 2, uint64(int64(o.Y)), 3, o.Rotate, 4, o.Index, 6, o.ID, 7, o.Status, 8, uint64(o.Start), 9, uint64(o.End))
+ for _, id := range sorted(o.Inner) {
+ b = wire.AppendBytes(b, 10, objectWire(o.Inner[id]))
+ }
+ return b
+}
+func placeWire(chunk uint64, objects ...*object) []byte {
+ b := row(1, chunk)
+ for _, o := range objects {
+ b = wire.AppendBytes(b, 2, objectWire(o))
+ }
+ return b
+}
+func parseObject(b []byte) *object {
+ return &object{X: int32(num(b, 1)), Y: int32(num(b, 2)), Rotate: num(b, 3), Index: num(b, 4), ID: num(b, 6), Inner: map[uint64]*object{}}
+}
+func itemWire(it item) []byte { return row(1, it.Index, 2, it.ID, 3, it.Type, 4, it.Count) }
+func growthWire(v *snapshot) []byte {
+ var b []byte
+ for i, x := range v.Growth {
+ b = wire.AppendVarint(b, i+1, x)
+ }
+ return b
+}
+func userWire(v *snapshot) []byte {
+ b := row(1, v.Coin, 2, v.World)
+ b = wire.AppendBytes(b, 3, growthWire(v))
+ for _, id := range sorted(v.Chunks) {
+ b = wire.AppendVarint(b, 4, id)
+ }
+ return b
+}
+func citizenWire(c citizen) []byte { return wire.AppendBytes(row(1, c.Index, 2, c.Slot), 3, c.Avatar) }
+func helperWire(h helper) []byte {
+ b := row(1, h.Index, 2, h.ID, 3, h.Slot, 6, h.Work, 7, h.WorkID, 8, uint64(h.Assigned))
+ b = wire.AppendString(b, 4, h.Name)
+ return wire.AppendBytes(b, 5, h.Avatar)
+}
+func (s *Service) info(v *snapshot, full bool) []byte {
+ b := wire.AppendBytes(nil, 2, userWire(v))
+ cf, hf := 3, 4
+ if full {
+ cf, hf = 7, 9
+ for _, chunk := range sorted(v.Objects) {
+ keys := make([]string, 0, len(v.Objects[chunk]))
+ for key := range v.Objects[chunk] {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ p := row(1, chunk)
+ for _, key := range keys {
+ p = wire.AppendBytes(p, 2, objectWire(v.Objects[chunk][key]))
+ }
+ b = wire.AppendBytes(b, 1, p)
+ }
+ keys := make([]string, 0, len(v.Items))
+ for key := range v.Items {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ for _, key := range keys {
+ it := v.Items[key]
+ if it.Count == 0 {
+ continue
+ }
+ f := 3
+ if it.Type == 65 {
+ f = 4
+ }
+ b = wire.AppendBytes(b, f, itemWire(it))
+ }
+ for _, group := range sorted(v.Tools) {
+ b = wire.AppendBytes(b, 5, row(1, group, 2, v.Tools[group]))
+ }
+ for _, id := range sorted(v.Foods) {
+ if v.Foods[id] > s.options.Now().Unix() {
+ b = wire.AppendBytes(b, 6, row(1, id, 2, uint64(v.Foods[id])))
+ }
+ }
+ for _, id := range sorted(v.Collections) {
+ b = wire.AppendVarint(b, 8, id)
+ }
+ for _, slot := range sorted(v.Candidates) {
+ g := row(1, slot)
+ for _, h := range v.Candidates[slot] {
+ g = wire.AppendBytes(g, 2, helperWire(h))
+ }
+ b = wire.AppendBytes(b, 10, g)
+ }
+ }
+ for _, slot := range sorted(v.Citizens) {
+ b = wire.AppendBytes(b, cf, citizenWire(v.Citizens[slot]))
+ }
+ for _, id := range sorted(v.Helpers) {
+ b = wire.AppendBytes(b, hf, helperWire(v.Helpers[id]))
+ }
+ return b
+}
+
+var routes = map[string]int{"/LifeWorldChoice": 593, "/LifeUserInfo": 594, "/LifeInfo": 595, "/LifeWorldObjectPositionSave": 596, "/LifeWorldObjectGathering": 597, "/LifeShopBuy": 598, "/LifeSeeding": 599, "/LifeToolUpgrade": 600, "/LifeEatFood": 601, "/LifeShopSell": 602, "/LifeShopBuyInfo": 603, "/LifeWorldObjectPlaceSave": 604, "/LifeWorldObjectBuildCompleted": 605, "/LifeCooking": 606, "/LifeCrafting": 607, "/LifeWorldObjectUnplaceSave": 608, "/LifeWorldChunkExpand": 609, "/LifeCitizenRecruit": 610, "/LifeCitizenAvatarSave": 611, "/LifeHelperGacha": 615, "/LifeHelperRecruit": 616, "/LifeHelperFire": 617, "/LifeHelperReName": 618, "/LifeHelperAssign": 619, "/LifeHelperReward": 620, "/LifeHelperReconnect": 628, "/LifeHelperRewardInfo": 629, "/LifeHelperGachaDelete": 630, "/LifeWorldObjectPositionDeltaSave": 634}
+
+func (s *Service) Handle(ctx command.Context, path string, request []byte) (int, []byte, bool, error) {
+ code, handled := routes[path]
+ if !handled {
+ return 0, nil, false, nil
+ }
+ fail := func(err error) (int, []byte, bool, error) { return code, nil, true, err }
+ if err := wire.Walk(request, func(wire.Field) error { return nil }); err != nil {
+ return fail(err)
+ }
+ seq := num(request, 1)
+ if seq == 0 || seq > math.MaxInt32 || ctx.SessionID == "" {
+ return fail(ErrInvalid)
+ }
+ v, err := s.load(ctx)
+ if err != nil {
+ return fail(err)
+ }
+ if path == "/LifeUserInfo" || path == "/LifeInfo" {
+ if err := s.refresh(v); err != nil {
+ return fail(err)
+ }
+ if err := save(ctx, v); err != nil {
+ return fail(err)
+ }
+ return code, s.info(v, path == "/LifeInfo"), true, nil
+ }
+ if path == "/LifeShopBuyInfo" {
+ return code, s.shopInfo(v), true, nil
+ }
+ if path == "/LifeHelperRewardInfo" {
+ b, err := s.helperPreview(v)
+ return code, b, true, err
+ }
+ key := ctx.SessionID + ":" + path
+ old, found, err := ctx.State.LoadEntry("missions", "life_receipts", key)
+ if err != nil {
+ return fail(err)
+ }
+ if found {
+ var r receipt
+ if err := json.Unmarshal(old, &r); err != nil {
+ return fail(err)
+ }
+ if seq == r.Sequence {
+ if !bytes.Equal(r.Request, request) {
+ return fail(ErrInvalid)
+ }
+ return code, r.Body, true, nil
+ }
+ if seq < r.Sequence {
+ return fail(ErrInvalid)
+ }
+ }
+ if err := s.refresh(v); err != nil {
+ return fail(err)
+ }
+ body, err := s.apply(ctx, v, path, request)
+ if err != nil {
+ return fail(err)
+ }
+ raw, err := json.Marshal(receipt{Request: request, Body: body, Sequence: seq})
+ if err != nil {
+ return fail(err)
+ }
+ if err := save(ctx, v, stateio.EntryMutation{Bucket: "life_receipts", Key: key, Payload: raw}); err != nil {
+ return fail(err)
+ }
+ return code, body, true, nil
+}
+
+func (s *Service) Apply(ctx command.Context, key string, costs, gains []gamedata.Reward) ([]byte, error) {
+ if key == "" {
+ return nil, ErrInvalid
+ }
+ request, err := json.Marshal(struct{ Costs, Gains []gamedata.Reward }{costs, gains})
+ if err != nil {
+ return nil, err
+ }
+ raw, found, err := ctx.State.LoadEntry("missions", "life_economy", key)
+ if err != nil {
+ return nil, err
+ }
+ if found {
+ var r receipt
+ if err := json.Unmarshal(raw, &r); err != nil {
+ return nil, err
+ }
+ if !bytes.Equal(r.Request, request) {
+ return nil, ErrInvalid
+ }
+ return r.Body, nil
+ }
+ v, err := s.load(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if err = s.spend(v, costs); err != nil {
+ return nil, err
+ }
+ body, err := s.grant(v, gains)
+ if err != nil {
+ return nil, err
+ }
+ raw, err = json.Marshal(receipt{Request: request, Body: body})
+ if err != nil {
+ return nil, err
+ }
+ return body, save(ctx, v, stateio.EntryMutation{Bucket: "life_economy", Key: key, Payload: raw})
+}
+func (s *Service) CanApply(ctx command.Context, costs, gains []gamedata.Reward) error {
+ v, err := s.load(ctx)
+ if err != nil {
+ return err
+ }
+ if err := s.spend(v, costs); err != nil {
+ return err
+ }
+ _, err = s.grant(v, gains)
+ return err
+}
+func (s *Service) Items(ctx command.Context) ([][]byte, error) {
+ v, err := s.load(ctx)
+ if err != nil {
+ return nil, err
+ }
+ var out [][]byte
+ keys := make([]string, 0, len(v.Items))
+ for key := range v.Items {
+ keys = append(keys, key)
+ }
+ sort.Strings(keys)
+ for _, key := range keys {
+ if it := v.Items[key]; it.Count > 0 {
+ out = append(out, itemWire(it))
+ }
+ }
+ return out, nil
+}
+func (s *Service) Coin(ctx command.Context) (uint64, error) { return s.Balance(ctx, 64, 0) }
+func (s *Service) Balance(ctx command.Context, typ, id uint64) (uint64, error) {
+ v, err := s.load(ctx)
+ if err != nil {
+ return 0, err
+ }
+ if typ == 64 {
+ return v.Coin, nil
+ }
+ return v.Items[itemKey(typ, id)].Count, nil
+}
+func (s *Service) spend(v *snapshot, costs []gamedata.Reward) error {
+ for _, r := range costs {
+ if r.Count == 0 || r.Count > math.MaxInt32 {
+ return ErrInvalid
+ }
+ switch r.Type {
+ case 64:
+ if v.Coin < r.Count {
+ return ErrFunds
+ }
+ v.Coin -= r.Count
+ case 65, 66:
+ key := itemKey(r.Type, r.ID)
+ it := v.Items[key]
+ if it.Count < r.Count {
+ return ErrFunds
+ }
+ it.Count -= r.Count
+ v.Items[key] = it
+ default:
+ return ErrInvalid
+ }
+ }
+ return nil
+}
+func (s *Service) grant(v *snapshot, gains []gamedata.Reward) ([]byte, error) {
+ var b []byte
+ for _, r := range gains {
+ if r.Count == 0 || r.Count > math.MaxInt32 {
+ return nil, ErrInvalid
+ }
+ it := item{Type: r.Type, ID: r.ID}
+ switch r.Type {
+ case 64:
+ if v.Coin > math.MaxInt32-r.Count {
+ return nil, ErrInvalid
+ }
+ v.Coin += r.Count
+ it.Count = v.Coin
+ case 65, 66:
+ if r.Type == 66 && s.design.Row("LifeItemTable", r.ID) == nil || r.Type == 65 && s.design.Row("LifeObjectGroupTable", r.ID) == nil {
+ return nil, ErrInvalid
+ }
+ key := itemKey(r.Type, r.ID)
+ it = v.Items[key]
+ if it.Index == 0 {
+ it = item{Index: v.Next, Type: r.Type, ID: r.ID}
+ v.Next++
+ }
+ if it.Count > math.MaxInt32-r.Count {
+ return nil, ErrInvalid
+ }
+ it.Count += r.Count
+ if r.Type == 66 {
+ limit := num(s.design.Row("LifeItemTable", r.ID), 8)
+ if limit > 0 && it.Count > limit {
+ return nil, fmt.Errorf("life: item stack full")
+ }
+ }
+ v.Items[key] = it
+ default:
+ return nil, ErrInvalid
+ }
+ for _, id := range s.design.CollectionsByItem[[2]uint64{r.Type, r.ID}] {
+ v.Collections[id] = true
+ }
+ b = wire.AppendBytes(b, 1, itemWire(it))
+ b = wire.AppendBytes(b, 6, itemWire(item{ID: r.ID, Type: r.Type, Count: r.Count}))
+ }
+ return b, nil
+}
diff --git a/go/internal/server/domain/life/life_test.go b/go/internal/server/domain/life/life_test.go
new file mode 100644
index 0000000..2e69e1f
--- /dev/null
+++ b/go/internal/server/domain/life/life_test.go
@@ -0,0 +1,300 @@
+package life_test
+
+import (
+ "bytes"
+ "errors"
+ "testing"
+ "time"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/life"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+// This deliberately small economy is a gameplay scenario, independent of the
+// installed IDs/prices. Field numbers come from the extracted 2.36.7 Proto;
+// worker quantity/cycle and the settlement cap come from PackInfoLife.cs and
+// LifePacket.CanSettlementHelperReward. No production encoder is used here.
+func proto(values ...uint64) []byte {
+ var b []byte
+ for i := 0; i < len(values); i += 2 {
+ b = wire.AppendVarint(b, int(values[i]), values[i+1])
+ }
+ return b
+}
+func child(b []byte, field int, value []byte) []byte { return wire.AppendBytes(b, field, value) }
+func scalar(t *testing.T, b []byte, field int) uint64 {
+ t.Helper()
+ v, _, err := wire.Varint(b, field)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return v
+}
+func nested(t *testing.T, b []byte, field int) []byte {
+ t.Helper()
+ v, ok, err := wire.Bytes(b, field)
+ if err != nil || !ok {
+ t.Fatalf("missing message field %d: %x (%v)", field, b, err)
+ }
+ return v
+}
+func repeated(t *testing.T, b []byte, field int) [][]byte {
+ t.Helper()
+ var out [][]byte
+ if err := wire.Walk(b, func(f wire.Field) error {
+ if f.Number == field && f.Type == 2 {
+ out = append(out, f.Value)
+ }
+ return nil
+ }); err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+func catalog(t *testing.T) *gamedata.LifeCatalog {
+ t.Helper()
+ tables := map[string][][]byte{
+ "LifeDefaultTable": {proto(21, 0, 4, 5, 18, 2, 19, 7, 20, 10, 26, 25)},
+ "LifeWorldTable": {proto(4, 91, 1, 1), proto(4, 92, 1, 1)},
+ "LifeDefaultObjectGroupTable": {proto(3, 1, 8, 91, 1, 1, 2, 301, 4, 3, 5, 2, 6, 3), proto(3, 2, 8, 92, 1, 1, 2, 301, 4, 3, 5, 2, 6, 3)},
+ "LifeObjectGroupTable": {proto(5, 301, 12, 3, 7, 1), proto(5, 302, 12, 3, 7, 1, 9, 1), proto(5, 303, 12, 3, 7, 1, 9, 1)},
+ "LifeBuildingObjectTable": {proto(4, 301, 2, 1, 3, 30, 5, 1, 7, 1), proto(4, 302, 2, 102, 11, 5, 8, 3, 9, 501, 10, 66), proto(4, 303, 2, 101, 11, 5, 8, 2, 9, 501, 10, 66)},
+ "LifeGatheringObjectTable": {proto(4, 301, 6, 1, 10, 1, 1, 3, 2, 1, 3, 100, 8, 2, 9, 10)},
+ "LifeItemTable": {proto(5, 501, 10, 10, 3, 1, 8, 1000)},
+ "LifeHelperSpeciesTable": {proto(9, 71, 10, 1, 1, 801, 2, 2, 3, 4, 4, 3, 6, 901, 8, 902)},
+ "LifeCharGrowthTable": {proto(2, 1, 3, 1, 4, 3), proto(2, 1, 3, 2, 4, 9), proto(2, 2, 3, 1, 4, 5), proto(2, 3, 3, 1, 4, 5)},
+ "LifeBuyItemTable": {proto(1, 6, 2, 8, 3, 2, 4, 501, 5, 66, 6, 3, 8, 64, 9, 2, 10, 1)},
+ }
+ d, err := gamedata.NewLifeCatalog(tables)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return d
+}
+
+type game struct {
+ t *testing.T
+ ctx command.Context
+ s *life.Service
+ d *gamedata.LifeCatalog
+ now time.Time
+ seq uint64
+ options life.Options
+}
+
+func scenario(t *testing.T) *game {
+ t.Helper()
+ g := &game{t: t, ctx: command.Context{Identity: command.Identity{AccountID: "player", SessionID: "session"}, State: stateio.NewMemory()}, d: catalog(t), now: time.Date(2026, 4, 12, 12, 0, 0, 0, time.UTC)}
+ g.options = life.Options{Now: func() time.Time { return g.now }, Sample: func(uint64) (uint64, error) { return 0, nil }, ValidateAvatar: func(_ command.Context, b []byte) error {
+ if scalar(t, b, 1) != 801 {
+ return errors.New("not owned")
+ }
+ return nil
+ }}
+ g.reopen()
+ return g
+}
+func (g *game) reopen() {
+ g.t.Helper()
+ var err error
+ g.s, err = life.Open(g.ctx, g.d, g.options)
+ if err != nil {
+ g.t.Fatal(err)
+ }
+}
+func (g *game) request(path string, b []byte) ([]byte, error) {
+ g.t.Helper()
+ g.seq++
+ b = append(proto(1, g.seq), b...)
+ _, out, handled, err := g.s.Handle(g.ctx, path, b)
+ if !handled {
+ g.t.Fatalf("unhandled %s", path)
+ }
+ return out, err
+}
+func (g *game) call(path string, b []byte) []byte {
+ g.t.Helper()
+ out, err := g.request(path, b)
+ if err != nil {
+ g.t.Fatalf("%s: %v", path, err)
+ }
+ return out
+}
+func (g *game) fund(key string, coin, wood uint64) {
+ g.t.Helper()
+ var rewards []gamedata.Reward
+ if coin > 0 {
+ rewards = append(rewards, gamedata.Reward{Type: 64, Count: coin})
+ }
+ if wood > 0 {
+ rewards = append(rewards, gamedata.Reward{Type: 66, ID: 501, Count: wood})
+ }
+ if _, err := g.s.Apply(g.ctx, key, nil, rewards); err != nil {
+ g.t.Fatal(err)
+ }
+}
+func placement(id, x, y uint64) []byte { return child(proto(1, 1), 2, proto(6, id, 1, x, 2, y)) }
+func (g *game) build(id, x, y uint64) []byte {
+ g.t.Helper()
+ p := placement(id, x, y)
+ g.call("/LifeWorldObjectPlaceSave", child(nil, 2, p))
+ if _, err := g.request("/LifeWorldObjectBuildCompleted", child(nil, 2, p)); !errors.Is(err, life.ErrInvalid) {
+ g.t.Fatalf("early completion: %v", err)
+ }
+ g.now = g.now.Add(5 * time.Second)
+ return nested(g.t, g.call("/LifeWorldObjectBuildCompleted", child(nil, 2, p)), 1)
+}
+
+func TestResidentsWorkersGrowthAndCurrencySurviveRealActionFlow(t *testing.T) {
+ g := scenario(t)
+ initial := g.call("/LifeUserInfo", nil)
+ user := nested(t, initial, 2)
+ if scalar(t, user, 2) != 0 || scalar(t, nested(t, user, 3), 1) != 1 {
+ t.Fatal("new player must have real unselected world and initial growth")
+ }
+ g.call("/LifeWorldChoice", proto(2, 91))
+ g.fund("mail-grant", 20, 8)
+ house := g.build(302, 5, 6)
+ avatar := proto(1, 801, 2, 901)
+ citizen := nested(t, g.call("/LifeCitizenRecruit", child(child(nil, 2, house), 3, child(nil, 3, avatar))), 1)
+ workerHouse := g.build(303, 8, 9)
+ candidate := repeated(t, g.call("/LifeHelperGacha", child(nil, 2, workerHouse)), 1)[0]
+ recruit := child(child(nil, 3, candidate), 4, workerHouse)
+ g.call("/LifeHelperRecruit", recruit)
+ helper := child(proto(1, scalar(t, candidate, 1), 6, 1), 5, avatar)
+ g.call("/LifeHelperAssign", child(child(nil, 2, helper), 3, workerHouse))
+ g.now = g.now.Add(20 * time.Second)
+ preview := g.call("/LifeHelperRewardInfo", nil)
+ previewItems := repeated(t, nested(t, preview, 2), 1)
+ if len(previewItems) != 1 || scalar(t, previewItems[0], 4) != 8 {
+ t.Fatalf("two work cycles at four per cycle: %x", preview)
+ }
+ before, _ := g.s.Balance(g.ctx, 66, 501)
+ g.call("/LifeHelperRewardInfo", nil)
+ after, _ := g.s.Balance(g.ctx, 66, 501)
+ if before != after {
+ t.Fatal("reward preview granted inventory")
+ }
+ g.seq++
+ claim := proto(1, g.seq)
+ _, first, _, err := g.s.Handle(g.ctx, "/LifeHelperReward", claim)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, again, _, err := g.s.Handle(g.ctx, "/LifeHelperReward", claim)
+ if err != nil || !bytes.Equal(first, again) {
+ t.Fatal("identical settlement retry must replay")
+ }
+ g.reopen()
+ g.ctx.SessionID = "relogin"
+ restored := g.call("/LifeUserInfo", nil)
+ if len(repeated(t, restored, 3)) != 1 || !bytes.Equal(nested(t, restored, 3), citizen) || len(repeated(t, restored, 4)) != 1 {
+ t.Fatalf("lost residents or helpers: %x", restored)
+ }
+ if coin, _ := g.s.Coin(g.ctx); coin != 13 {
+ t.Fatalf("hire did not consume the persisted mail currency: %d", coin)
+ }
+ balance, _ := g.s.Balance(g.ctx, 66, 501)
+ if balance != 11 {
+ t.Fatalf("materials: want initial 8 - building 5 + helper 8, got %d", balance)
+ }
+ forest := placement(301, 2, 3)
+ forestObject := nested(t, forest, 2)
+ forestObject = child(forestObject, 10, proto(6, 1, 4, 0, 7, 999))
+ gather := child(nil, 2, child(proto(1, 1), 2, forestObject))
+ g.call("/LifeWorldObjectGathering", gather)
+ if _, err := g.request("/LifeWorldObjectGathering", gather); err == nil {
+ t.Fatal("gathered resource granted twice before regeneration")
+ }
+ g.reopen()
+ current := nested(t, g.call("/LifeUserInfo", nil), 2)
+ growth := nested(t, current, 3)
+ if scalar(t, growth, 1) != 2 || scalar(t, growth, 2) != 0 {
+ t.Fatalf("earned experience did not advance level across relog: %x", growth)
+ }
+ g.now = g.now.Add(30 * time.Second)
+ g.call("/LifeWorldObjectGathering", gather)
+ g.call("/LifeWorldChoice", proto(2, 92))
+ reset := g.call("/LifeUserInfo", nil)
+ if len(repeated(t, reset, 3)) != 0 || scalar(t, nested(t, reset, 4), 3) != 0 {
+ t.Fatal("terrain reset did not release residents/helpers")
+ }
+ if scalar(t, nested(t, nested(t, reset, 2), 3), 1) != 2 {
+ t.Fatal("terrain reset erased earned growth")
+ }
+}
+
+func TestShopLimitResetAndRejectedOperationsLeaveCurrencyUntouched(t *testing.T) {
+ g := scenario(t)
+ g.fund("mail", 20, 0)
+ g.call("/LifeShopBuy", proto(2, 6, 3, 8, 4, 2))
+ if _, err := g.request("/LifeShopBuy", proto(2, 6, 3, 8, 4, 1)); err == nil {
+ t.Fatal("daily purchase limit bypassed")
+ }
+ if coin, _ := g.s.Coin(g.ctx); coin != 14 {
+ t.Fatal("rejected purchase charged currency")
+ }
+ g.reopen()
+ if info := g.call("/LifeShopBuyInfo", nil); scalar(t, nested(t, info, 1), 3) != 2 {
+ t.Fatal("purchase count lost on reload")
+ }
+ g.now = g.now.Add(24 * time.Hour)
+ g.call("/LifeShopBuy", proto(2, 6, 3, 8, 4, 1))
+ if coin, _ := g.s.Coin(g.ctx); coin != 11 {
+ t.Fatal("daily reset did not reopen purchase")
+ }
+ if err := g.s.CanApply(g.ctx, []gamedata.Reward{{Type: 64, Count: 50}}, nil); !errors.Is(err, life.ErrFunds) {
+ t.Fatalf("CanApply funds: %v", err)
+ }
+ if coin, _ := g.s.Coin(g.ctx); coin != 11 {
+ t.Fatal("validation changed funds")
+ }
+ before, _ := g.s.Items(g.ctx)
+ if _, err := g.s.Apply(g.ctx, "bad", []gamedata.Reward{{Type: 64, Count: 1}}, []gamedata.Reward{{Type: 66, ID: 9999, Count: 1}}); err == nil {
+ t.Fatal("invalid reward should abort both sides")
+ }
+ after, _ := g.s.Items(g.ctx)
+ if !bytes.Equal(bytes.Join(before, nil), bytes.Join(after, nil)) {
+ t.Fatal("failed economy altered inventory")
+ }
+ if coin, _ := g.s.Coin(g.ctx); coin != 11 {
+ t.Fatal("failed reward retained debit")
+ }
+}
+
+type failStore struct {
+ stateio.AtomicEntryStore
+ fail bool
+}
+
+func (s *failStore) SaveWithEntries(domain string, core []byte, changes []stateio.EntryMutation) error {
+ if s.fail {
+ return errors.New("injected atomic write failure")
+ }
+ return s.AtomicEntryStore.SaveWithEntries(domain, core, changes)
+}
+func TestAtomicWriteFailureDoesNotLeakCandidateStateOrReceipt(t *testing.T) {
+ g := scenario(t)
+ store := &failStore{AtomicEntryStore: g.ctx.State}
+ g.ctx.State = store
+ g.fund("mail", 20, 0)
+ store.fail = true
+ req := proto(1, 7, 2, 6, 3, 8, 4, 1)
+ if _, _, _, err := g.s.Handle(g.ctx, "/LifeShopBuy", req); err == nil {
+ t.Fatal("write failure swallowed")
+ }
+ store.fail = false
+ g.reopen()
+ if coin, _ := g.s.Coin(g.ctx); coin != 20 {
+ t.Fatal("uncommitted debit leaked")
+ }
+ if _, _, _, err := g.s.Handle(g.ctx, "/LifeShopBuy", req); err != nil {
+ t.Fatalf("retry after failed commit: %v", err)
+ }
+ if coin, _ := g.s.Coin(g.ctx); coin != 17 {
+ t.Fatal("successful retry must charge once")
+ }
+}
diff --git a/go/internal/server/domain/life/world.go b/go/internal/server/domain/life/world.go
new file mode 100644
index 0000000..459779c
--- /dev/null
+++ b/go/internal/server/domain/life/world.go
@@ -0,0 +1,600 @@
+package life
+
+import (
+ "fmt"
+ "math"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+)
+
+func (s *Service) apply(ctx command.Context, v *snapshot, path string, req []byte) ([]byte, error) {
+ switch path {
+ case "/LifeWorldChoice":
+ return s.choose(v, num(req, 2))
+ case "/LifeWorldChunkExpand":
+ chunk := num(req, 2)
+ if v.World == 0 || chunk == 0 || chunk > s.design.MaxChunks || uint64(len(v.Chunks)) >= s.design.MaxChunks || v.Chunks[chunk] {
+ return nil, ErrInvalid
+ }
+ d := s.design.Row("LifeChunkExpandTable", uint64(len(v.Chunks)))
+ if d == nil {
+ return nil, ErrInvalid
+ }
+ cost, err := costs(d, 7, 6, 5, 1)
+ if err != nil {
+ return nil, err
+ }
+ if err = s.spend(v, cost); err != nil {
+ return nil, err
+ }
+ v.ExpansionRefund = append(v.ExpansionRefund, cost...)
+ v.Chunks[chunk] = true
+ v.Objects[chunk] = map[string]*object{}
+ return wire.AppendBytes(nil, 1, userWire(v)), nil
+ case "/LifeWorldObjectPlaceSave":
+ return s.place(v, msg(req, 2))
+ case "/LifeWorldObjectBuildCompleted":
+ return s.complete(v, msg(req, 2))
+ case "/LifeWorldObjectUnplaceSave":
+ return s.unplace(v, msg(req, 2))
+ case "/LifeWorldObjectPositionSave":
+ return nil, s.move(v, messages(req, 2))
+ case "/LifeWorldObjectPositionDeltaSave":
+ return nil, s.delta(v, req)
+ case "/LifeWorldObjectGathering":
+ return s.gather(v, messages(req, 2))
+ case "/LifeSeeding":
+ return s.seed(v, messages(req, 2))
+ case "/LifeCrafting", "/LifeCooking", "/LifeToolUpgrade", "/LifeEatFood", "/LifeShopBuy", "/LifeShopSell":
+ return s.economy(v, path, req)
+ case "/LifeCitizenRecruit", "/LifeCitizenAvatarSave":
+ return s.citizen(ctx, v, path, req)
+ default:
+ return s.helpers(v, path, req)
+ }
+}
+func costs(raw []byte, typ, id, count int, mult uint64) ([]gamedata.Reward, error) {
+ ts, is, cs := ints(raw, typ), ints(raw, id), ints(raw, count)
+ if len(ts) != len(is) || len(is) != len(cs) {
+ return nil, ErrInvalid
+ }
+ var out []gamedata.Reward
+ for i, t := range ts {
+ if cs[i] == 0 {
+ continue
+ }
+ if mult == 0 || cs[i] > math.MaxInt32/mult {
+ return nil, ErrInvalid
+ }
+ out = append(out, gamedata.Reward{Type: t, ID: is[i], Count: cs[i] * mult})
+ }
+ return out, nil
+}
+func (s *Service) choose(v *snapshot, world uint64) ([]byte, error) {
+ d := s.design.Row("LifeWorldTable", world)
+ if d == nil || world == 0 {
+ return nil, ErrInvalid
+ }
+ if v.World == world {
+ return nil, ErrInvalid
+ }
+ refunds := append([]gamedata.Reward(nil), v.ExpansionRefund...)
+ for _, objects := range v.Objects {
+ for _, o := range objects {
+ refunds = append(refunds, o.Refund...)
+ }
+ }
+ bundle, err := s.grant(v, refunds)
+ if err != nil {
+ return nil, err
+ }
+ v.World = world
+ v.Chunks = map[uint64]bool{}
+ v.Objects = map[uint64]map[string]*object{}
+ v.Counts = map[uint64]uint64{}
+ v.ActiveCounts = map[uint64]uint64{}
+ v.Layers = map[uint64]uint64{}
+ v.Citizens = map[uint64]citizen{}
+ v.Candidates = map[uint64][]helper{}
+ v.ExpansionRefund = nil
+ for id, h := range v.Helpers {
+ h.Slot = 0
+ h.Assigned = 0
+ h.Work = 0
+ h.WorkID = 0
+ v.Helpers[id] = h
+ }
+ for _, id := range ints(d, 1) {
+ v.Chunks[id] = true
+ v.Objects[id] = map[string]*object{}
+ }
+ for _, r := range s.design.WorldDefaults[world] {
+ chunk := num(r, 1)
+ if !v.Chunks[chunk] {
+ return nil, fmt.Errorf("life: default object outside initial chunks")
+ }
+ o := &object{ID: num(r, 2), X: int32(num(r, 5)), Y: int32(num(r, 6)), Rotate: num(r, 7), Index: v.Next, Status: 1, Inner: map[uint64]*object{}}
+ v.Next++
+ if err := s.initResources(o); err != nil {
+ return nil, err
+ }
+ if err := s.insert(v, chunk, o); err != nil {
+ return nil, err
+ }
+ }
+ b := wire.AppendBytes(nil, 1, bundle)
+ for _, id := range sorted(v.Chunks) {
+ b = wire.AppendVarint(b, 2, id)
+ }
+ return b, nil
+}
+func (s *Service) initResources(o *object) error {
+ d := s.design.Row("LifeBuildingObjectTable", o.ID)
+ function := num(d, 2)
+ if function != 1 && function != 2 {
+ return nil
+ }
+ count := num(d, 5)
+ if count > num(d, 7) || count > 256 {
+ return ErrInvalid
+ }
+ for i := range count {
+ r, err := s.randomGather(o.ID)
+ if err != nil {
+ return err
+ }
+ o.Inner[i] = &object{ID: num(r, 6), Index: i, Status: num(r, 10), Start: s.options.Now().Unix(), Inner: map[uint64]*object{}}
+ }
+ return nil
+}
+func (s *Service) randomGather(group uint64) ([]byte, error) {
+ variants := s.design.Gathering[group]
+ var total uint64
+ ids := sorted(variants)
+ for _, id := range ids {
+ r := variants[id]
+ if len(r) > 0 {
+ total += num(r[0], 3)
+ }
+ }
+ if total == 0 {
+ return nil, ErrInvalid
+ }
+ pick, err := s.options.Sample(total)
+ if err != nil || pick >= total {
+ return nil, ErrInvalid
+ }
+ for _, id := range ids {
+ rs := variants[id]
+ w := num(rs[0], 3)
+ if pick < w {
+ return rs[len(rs)-1], nil
+ }
+ pick -= w
+ }
+ return nil, ErrInvalid
+}
+func (s *Service) insert(v *snapshot, chunk uint64, o *object) error {
+ if !v.Chunks[chunk] || o.ID == 0 || o.Rotate > 3 || v.Objects[chunk][objectKey(o)] != nil {
+ return ErrInvalid
+ }
+ if v.Objects[chunk] == nil {
+ v.Objects[chunk] = map[string]*object{}
+ }
+ v.Objects[chunk][objectKey(o)] = o
+ v.Counts[o.ID]++
+ if o.Status > 0 {
+ v.ActiveCounts[o.ID]++
+ }
+ g := s.design.Row("LifeObjectGroupTable", o.ID)
+ if num(g, 12) == 4 {
+ v.Layers[num(g, 8)]++
+ }
+ return nil
+}
+func (s *Service) remove(v *snapshot, chunk uint64, o *object) {
+ delete(v.Objects[chunk], objectKey(o))
+ v.Counts[o.ID]--
+ if o.Status > 0 {
+ v.ActiveCounts[o.ID]--
+ }
+ g := s.design.Row("LifeObjectGroupTable", o.ID)
+ if num(g, 12) == 4 {
+ v.Layers[num(g, 8)]--
+ }
+}
+func (s *Service) selected(v *snapshot, raw []byte) (uint64, *object, error) {
+ chunk := num(raw, 1)
+ os := messages(raw, 2)
+ if !v.Chunks[chunk] || len(os) != 1 {
+ return 0, nil, ErrInvalid
+ }
+ wanted := parseObject(os[0])
+ o := v.Objects[chunk][objectKey(wanted)]
+ if o == nil {
+ return 0, nil, ErrInvalid
+ }
+ return chunk, o, nil
+}
+func (s *Service) place(v *snapshot, raw []byte) ([]byte, error) {
+ chunk := num(raw, 1)
+ os := messages(raw, 2)
+ if !v.Chunks[chunk] || len(os) != 1 {
+ return nil, ErrInvalid
+ }
+ o := parseObject(os[0])
+ g := s.design.Row("LifeObjectGroupTable", o.ID)
+ if g == nil || num(g, 7) == 0 || o.Rotate > 3 {
+ return nil, ErrInvalid
+ }
+ if group, level := num(g, 14), num(g, 13); group > 0 && (group > 3 || v.Growth[(group-1)*2] < level) {
+ return nil, ErrInvalid
+ }
+ typ := num(g, 12)
+ limit := num(g, 9)
+ if limit > 0 && v.Counts[o.ID] >= limit {
+ return nil, ErrInvalid
+ }
+ var required []gamedata.Reward
+ var err error
+ switch typ {
+ case 1:
+ if v.Counts[o.ID] >= v.Items[itemKey(65, o.ID)].Count {
+ return nil, ErrFunds
+ }
+ case 3:
+ d := s.design.Row("LifeBuildingObjectTable", o.ID)
+ if d == nil {
+ return nil, ErrInvalid
+ }
+ required, err = costs(d, 10, 9, 8, 1)
+ o.Start = s.options.Now().Unix()
+ o.End = o.Start + int64(num(d, 11))
+ if num(d, 11) == 0 {
+ o.Status = 1
+ if err := s.initResources(o); err != nil {
+ return nil, err
+ }
+ }
+ case 4:
+ d := s.design.Row("LifeDecoObjectTable", o.ID)
+ if d == nil {
+ return nil, ErrInvalid
+ }
+ required, err = costs(d, 5, 4, 3, 1)
+ layer := num(g, 8)
+ ld := s.design.Row("LifeChunkExpandTable", uint64(len(v.Chunks)))
+ field := map[uint64]int{1: 3, 2: 2, 3: 1}[layer]
+ if field == 0 {
+ return nil, ErrInvalid
+ }
+ if maximum := num(ld, field); maximum > 0 && v.Layers[layer] >= maximum {
+ return nil, ErrInvalid
+ }
+ o.Status = 1
+ default:
+ return nil, ErrInvalid
+ }
+ if err != nil {
+ return nil, err
+ }
+ if err = s.spend(v, required); err != nil {
+ return nil, err
+ }
+ o.Refund = required
+ o.Index = v.Next
+ v.Next++
+ if err = s.insert(v, chunk, o); err != nil {
+ return nil, err
+ }
+ return wire.AppendBytes(nil, 1, placeWire(chunk, o)), nil
+}
+func (s *Service) complete(v *snapshot, raw []byte) ([]byte, error) {
+ chunk, o, err := s.selected(v, raw)
+ if err != nil {
+ return nil, err
+ }
+ if s.design.Row("LifeBuildingObjectTable", o.ID) == nil || o.Status != 0 || s.options.Now().Unix() < o.End {
+ return nil, ErrInvalid
+ }
+ o.Status = 1
+ v.ActiveCounts[o.ID]++
+ if err := s.initResources(o); err != nil {
+ return nil, err
+ }
+ return wire.AppendBytes(nil, 1, placeWire(chunk, o)), nil
+}
+func (s *Service) unplace(v *snapshot, raw []byte) ([]byte, error) {
+ chunk, o, err := s.selected(v, raw)
+ if err != nil {
+ return nil, err
+ }
+ g := s.design.Row("LifeObjectGroupTable", o.ID)
+ if num(g, 7) == 0 || v.Counts[o.ID] <= num(g, 10) {
+ return nil, ErrInvalid
+ }
+ bundle, err := s.grant(v, o.Refund)
+ if err != nil {
+ return nil, err
+ }
+ s.remove(v, chunk, o)
+ delete(v.Citizens, o.Index)
+ delete(v.Candidates, o.Index)
+ b := wire.AppendBytes(nil, 1, bundle)
+ for id, h := range v.Helpers {
+ if h.Slot == o.Index {
+ h.Slot = 0
+ h.Work = 0
+ h.WorkID = 0
+ h.Assigned = 0
+ v.Helpers[id] = h
+ b = wire.AppendBytes(b, 2, helperWire(h))
+ }
+ }
+ return b, nil
+}
+func (s *Service) move(v *snapshot, moves [][]byte) error {
+ if len(moves) == 0 || len(moves) > 512 {
+ return ErrInvalid
+ }
+ type movement struct {
+ chunk uint64
+ o *object
+ }
+ out := make([]movement, 0, len(moves))
+ for _, raw := range moves {
+ before, after := msg(raw, 1), msg(raw, 2)
+ chunk, o, err := s.selected(v, before)
+ if err != nil {
+ return err
+ }
+ if num(s.design.Row("LifeObjectGroupTable", o.ID), 7) == 0 {
+ return ErrInvalid
+ }
+ os := messages(after, 2)
+ if !v.Chunks[num(after, 1)] || len(os) != 1 {
+ return ErrInvalid
+ }
+ p := parseObject(os[0])
+ if p.ID != o.ID || p.Rotate > 3 {
+ return ErrInvalid
+ }
+ s.remove(v, chunk, o)
+ o.X, o.Y, o.Rotate = p.X, p.Y, p.Rotate
+ out = append(out, movement{num(after, 1), o})
+ }
+ for _, m := range out {
+ if err := s.insert(v, m.chunk, m.o); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+func (s *Service) delta(v *snapshot, req []byte) error {
+ moves := messages(req, 4)
+ dx, dy := num(req, 2), num(req, 3)
+ x, y := int64(dx>>1)^-int64(dx&1), int64(dy>>1)^-int64(dy&1)
+ if len(moves) == 0 {
+ return ErrInvalid
+ }
+ var plans [][]byte
+ for _, raw := range moves {
+ o := &object{ID: num(raw, 4), X: int32(num(raw, 2)), Y: int32(num(raw, 3)), Rotate: num(raw, 5)}
+ if int64(o.X)+x > math.MaxInt32 || int64(o.X)+x < math.MinInt32 || int64(o.Y)+y > math.MaxInt32 || int64(o.Y)+y < math.MinInt32 {
+ return ErrInvalid
+ }
+ before := placeWire(num(raw, 1), o)
+ o.X += int32(x)
+ o.Y += int32(y)
+ after := placeWire(num(raw, 1), o)
+ plans = append(plans, wire.AppendBytes(wire.AppendBytes(nil, 1, before), 2, after))
+ }
+ return s.move(v, plans)
+}
+func (s *Service) refresh(v *snapshot) error {
+ now := s.options.Now().Unix()
+ for _, objects := range v.Objects {
+ for _, o := range objects {
+ d := s.design.Row("LifeBuildingObjectTable", o.ID)
+ function := num(d, 2)
+ for slot, in := range o.Inner {
+ if in.Status == 0 && (function == 1 || function == 2) && now >= in.Start+int64(num(d, 3)) {
+ r, err := s.randomGather(o.ID)
+ if err != nil {
+ return err
+ }
+ first := s.design.Gathering[o.ID][num(r, 6)][0]
+ in = &object{ID: num(r, 6), Index: slot, Status: num(first, 10), Start: in.Start + int64(num(d, 3)), Inner: map[uint64]*object{}}
+ o.Inner[slot] = in
+ }
+ if function >= 1 && function <= 3 && in.Status > 0 {
+ rows := s.design.Gathering[o.ID][in.ID]
+ if len(rows) == 0 {
+ return ErrInvalid
+ }
+ elapsed := now - in.Start
+ stage := num(rows[0], 10)
+ for i, r := range rows {
+ duration := int64(num(r, 11))
+ if elapsed < duration || i == len(rows)-1 {
+ stage = num(r, 10)
+ break
+ }
+ elapsed -= duration
+ }
+ in.Status = stage
+ }
+ }
+ }
+ }
+ return nil
+}
+
+func (s *Service) growth(v *snapshot, group, exp uint64) error {
+ if group == 0 || group > 3 {
+ return ErrInvalid
+ }
+ i := (group - 1) * 2
+ v.Growth[i+1] += exp
+ maximum := num(s.design.Row("LifeDefaultTable", 0), 4)
+ for v.Growth[i] < maximum {
+ need := num(s.design.Row("LifeCharGrowthTable", group, v.Growth[i]), 4)
+ if need == 0 || v.Growth[i+1] < need {
+ break
+ }
+ v.Growth[i+1] -= need
+ v.Growth[i]++
+ }
+ return nil
+}
+func (s *Service) seed(v *snapshot, seeds [][]byte) ([]byte, error) {
+ if len(seeds) == 0 || len(seeds) > 128 {
+ return nil, ErrInvalid
+ }
+ var b []byte
+ for _, raw := range seeds {
+ place := msg(raw, 2)
+ chunk, o, err := s.selected(v, place)
+ if err != nil {
+ return nil, err
+ }
+ if num(s.design.Row("LifeBuildingObjectTable", o.ID), 2) != 3 || o.Status != 1 || len(o.Inner) != 0 {
+ return nil, ErrInvalid
+ }
+ os := messages(place, 2)
+ ins := messages(os[0], 10)
+ if len(ins) != 1 {
+ return nil, ErrInvalid
+ }
+ id := num(ins[0], 6)
+ d := s.design.Row("LifeCropSeedTable", id)
+ rows := s.design.Gathering[o.ID][id]
+ if d == nil || len(rows) == 0 {
+ return nil, ErrInvalid
+ }
+ cost := gamedata.Reward{Type: num(d, 6), ID: num(d, 5), Count: num(d, 4)}
+ if err := s.spend(v, []gamedata.Reward{cost}); err != nil {
+ return nil, err
+ }
+ now := s.options.Now().Unix()
+ o.Inner[0] = &object{ID: id, Index: 0, Status: num(rows[0], 10), Start: now, End: now + int64(num(d, 7)), Inner: map[uint64]*object{}}
+ b = wire.AppendBytes(b, 1, placeWire(chunk, o))
+ }
+ return b, nil
+}
+func (s *Service) gather(v *snapshot, places [][]byte) ([]byte, error) {
+ if len(places) == 0 || len(places) > 15 {
+ return nil, ErrInvalid
+ }
+ var bundle []byte
+ var changed []byte
+ newCollections := map[uint64]bool{}
+ changedChunk := uint64(0)
+ changedObjects := map[string]*object{}
+ mixedChunks := false
+ for _, raw := range places {
+ chunk := num(raw, 1)
+ os := messages(raw, 2)
+ if !v.Chunks[chunk] || len(os) == 0 {
+ return nil, ErrInvalid
+ }
+ for _, requestObject := range os {
+ p := parseObject(requestObject)
+ o := v.Objects[chunk][objectKey(p)]
+ if o == nil || o.Status != 1 {
+ return nil, ErrInvalid
+ }
+ ins := messages(requestObject, 10)
+ if len(ins) != 1 {
+ return nil, ErrInvalid
+ }
+ want := parseObject(ins[0])
+ in := o.Inner[want.Index]
+ if in == nil || in.ID != want.ID || in.Status == 0 {
+ return nil, ErrInvalid
+ }
+ d := s.design.Row("LifeGatheringObjectTable", o.ID, in.ID, in.Status)
+ if d == nil {
+ return nil, ErrInvalid
+ }
+ if in.End > 0 && s.options.Now().Unix() < in.End {
+ return nil, ErrInvalid
+ }
+ uniques, counts := ints(d, 9), ints(d, 8)
+ if len(uniques) != len(counts) {
+ return nil, ErrInvalid
+ }
+ var rewards []gamedata.Reward
+ function := num(s.design.Row("LifeBuildingObjectTable", o.ID), 2)
+ skill, bonus, err := s.stats(v, function)
+ if err != nil {
+ return nil, err
+ }
+ for i, unique := range uniques {
+ ids := s.design.ItemsByUnique[unique]
+ if len(ids) == 0 {
+ return nil, ErrInvalid
+ }
+ itemID := num(ids[0], 5)
+ if function == 3 {
+ grade, err := s.grade(min(skill, num(s.design.Row("LifeDefaultTable", 0), 25)))
+ if err != nil {
+ return nil, err
+ }
+ itemID, err = s.uniqueItem(unique, grade)
+ if err != nil {
+ return nil, err
+ }
+ }
+ count := counts[i] + bonus
+ if count > math.MaxInt32 {
+ return nil, ErrInvalid
+ }
+ rewards = append(rewards, gamedata.Reward{Type: 66, ID: itemID, Count: count})
+ for _, id := range s.design.CollectionsByItem[[2]uint64{66, itemID}] {
+ if !v.Collections[id] {
+ newCollections[id] = true
+ }
+ }
+ }
+ gain, err := s.grant(v, rewards)
+ if err != nil {
+ return nil, err
+ }
+ bundle = append(bundle, gain...)
+ if err := s.growth(v, num(s.design.Row("LifeBuildingObjectTable", o.ID), 2), num(d, 1)); err != nil {
+ return nil, err
+ }
+ if function == 3 {
+ delete(o.Inner, want.Index)
+ } else {
+ in.Status = 0
+ in.Start = s.options.Now().Unix()
+ in.End = 0
+ }
+ if changedChunk == 0 {
+ changedChunk = chunk
+ } else if changedChunk != chunk {
+ mixedChunks = true
+ }
+ changedObjects[objectKey(o)] = o
+ }
+ }
+ if !mixedChunks {
+ changed = placeWire(changedChunk)
+ for _, o := range changedObjects {
+ changed = wire.AppendBytes(changed, 2, objectWire(o))
+ }
+ }
+ b := wire.AppendBytes(nil, 1, growthWire(v))
+ b = wire.AppendBytes(b, 2, bundle)
+ if !mixedChunks {
+ b = wire.AppendBytes(b, 3, changed)
+ }
+ for _, id := range sorted(newCollections) {
+ b = wire.AppendVarint(b, 4, id)
+ }
+ return b, nil
+}
diff --git a/go/internal/server/domain/notice/board.go b/go/internal/server/domain/notice/board.go
index 28c1be4..f3a0583 100644
--- a/go/internal/server/domain/notice/board.go
+++ b/go/internal/server/domain/notice/board.go
@@ -21,6 +21,7 @@ const (
TypeNotice Type = 0
TypeEvent Type = 1
TypeUpdate Type = 2
+ TypeSurvey Type = 3
TypeEmergency Type = 4
TypeDeveloperNote Type = 5
)
@@ -32,6 +33,7 @@ type Block struct {
type Notice struct {
ID int32
+ SubType int32
Type Type
Thumbnail string
Start time.Time
@@ -141,7 +143,7 @@ func (b *Board) Replace(source string, notices []Notice) {
}
func equal(a, b Notice) bool {
- return a.ID == b.ID && a.Type == b.Type && a.Thumbnail == b.Thumbnail &&
+ return a.ID == b.ID && a.SubType == b.SubType && a.Type == b.Type && a.Thumbnail == b.Thumbnail &&
a.Start.Equal(b.Start) && a.End.Equal(b.End) && a.URL == b.URL && a.Pinned == b.Pinned && a.Sort == b.Sort &&
maps.EqualFunc(a.Text, b.Text, func(x, y Content) bool { return x.Title == y.Title && slices.Equal(x.Blocks, y.Blocks) })
}
diff --git a/go/internal/server/domain/notice/community.go b/go/internal/server/domain/notice/community.go
new file mode 100644
index 0000000..59ee1c6
--- /dev/null
+++ b/go/internal/server/domain/notice/community.go
@@ -0,0 +1,107 @@
+package notice
+
+import (
+ "encoding/json"
+ "fmt"
+ "slices"
+ "time"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+type communityEconomy interface {
+ Apply(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error)
+}
+
+type CommunityService struct {
+ Store stateio.Store
+ Design *gamedata.CommunityRewards
+ Board *Board
+ Economy communityEconomy
+ Now func() time.Time
+}
+
+type communityClaim struct {
+ Type, SubType uint64
+}
+
+func (s CommunityService) Handle(ctx command.Context, path string, request []byte) (int, []byte, bool, error) {
+ code := 289
+ if path == "/CommunityReward" {
+ code = 290
+ } else if path != "/CommunityRewardInfo" {
+ return 0, nil, false, nil
+ }
+ fail := func(err error) (int, []byte, bool, error) { return code, nil, true, err }
+ if seq, found, err := wire.Varint(request, 1); err != nil || !found || seq == 0 {
+ return fail(fmt.Errorf("community: invalid request sequence"))
+ }
+ if s.Store == nil || s.Design == nil || s.Economy == nil {
+ return fail(fmt.Errorf("community: missing dependencies"))
+ }
+ raw, err := s.Store.Load(ctx.State, "community_rewards")
+ if err != nil {
+ return fail(err)
+ }
+ claims := []communityClaim{}
+ if raw != nil {
+ if err := json.Unmarshal(raw, &claims); err != nil {
+ return fail(fmt.Errorf("community: invalid saved claims: %w", err))
+ }
+ }
+ if path == "/CommunityRewardInfo" {
+ var out []byte
+ for _, claim := range claims {
+ row := wire.AppendVarint(nil, 1, claim.Type)
+ row = wire.AppendVarint(row, 2, claim.SubType)
+ out = wire.AppendBytes(out, 1, row)
+ }
+ return code, out, true, nil
+ }
+ typ, _, err := wire.Varint(request, 2)
+ if err != nil || typ > 6 {
+ return fail(fmt.Errorf("community: invalid reward type"))
+ }
+ sub, _, err := wire.Varint(request, 3)
+ if err != nil || sub > 1<<31-1 || typ != 0 && sub != 0 {
+ return fail(fmt.Errorf("community: invalid reward identifier"))
+ }
+ rewards := s.Design.Community
+ if typ == 0 {
+ if s.Board == nil || sub == 0 {
+ return fail(&command.GameError{PacketCode: code, ErrorType: 1, Message: "survey unavailable"})
+ }
+ n, found := s.Board.Find(int32(sub))
+ now := time.Now()
+ if s.Now != nil {
+ now = s.Now()
+ }
+ if !found || n.Type != TypeSurvey || n.SubType <= 0 || now.Before(n.Start) || !now.Before(n.End) {
+ return fail(&command.GameError{PacketCode: code, ErrorType: 1, Message: "survey unavailable"})
+ }
+ sub = uint64(n.SubType)
+ rewards = s.Design.Survey
+ }
+ claim := communityClaim{Type: typ, SubType: sub}
+ if slices.ContainsFunc(claims, func(old communityClaim) bool {
+ return old.Type == typ && (typ != 0 || old.SubType >= sub)
+ }) {
+ return code, wire.AppendBytes(nil, 1, nil), true, nil
+ }
+ bundle, err := s.Economy.Apply(ctx, fmt.Sprintf("community:%d:%d", typ, sub), nil, rewards)
+ if err != nil {
+ return fail(err)
+ }
+ claims = append(claims, claim)
+ raw, err = json.Marshal(claims)
+ if err != nil {
+ return fail(err)
+ }
+ if err := s.Store.Save(ctx.State, "community_rewards", raw); err != nil {
+ return fail(err)
+ }
+ return code, wire.AppendBytes(nil, 1, bundle), true, nil
+}
diff --git a/go/internal/server/domain/notice/protocol_adapter.go b/go/internal/server/domain/notice/protocol_adapter.go
index 124e8bb..806ebe4 100644
--- a/go/internal/server/domain/notice/protocol_adapter.go
+++ b/go/internal/server/domain/notice/protocol_adapter.go
@@ -85,6 +85,9 @@ func encode(n Notice, locale string) []byte {
if n.Sort != 0 {
out = wire.AppendVarint(out, 11, uint64(n.Sort))
}
+ if n.SubType != 0 {
+ out = wire.AppendVarint(out, 12, uint64(n.SubType))
+ }
return out
}
diff --git a/go/internal/server/domain/profile/avatar_validation.go b/go/internal/server/domain/profile/avatar_validation.go
new file mode 100644
index 0000000..16cdb21
--- /dev/null
+++ b/go/internal/server/domain/profile/avatar_validation.go
@@ -0,0 +1,29 @@
+package profile
+
+import (
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+)
+
+func (s *AvatarService) ValidateAppearance(ctx command.Context, raw []byte) error {
+ var use AvatarUse
+ var err error
+ use.UseCharID, err = avatarNumber(raw, 1)
+ if err != nil {
+ return err
+ }
+ for i := range use.Parts {
+ use.Parts[i], err = avatarNumber(raw, i+2)
+ if err != nil {
+ return err
+ }
+ }
+ if err := wire.Walk(raw, func(wire.Field) error { return nil }); err != nil {
+ return err
+ }
+ owned, err := s.owned(ctx)
+ if err != nil {
+ return err
+ }
+ return s.validateUse(use, owned)
+}
diff --git a/go/internal/server/domain/ranking/castle.go b/go/internal/server/domain/ranking/castle.go
new file mode 100644
index 0000000..8df44ee
--- /dev/null
+++ b/go/internal/server/domain/ranking/castle.go
@@ -0,0 +1,173 @@
+package ranking
+
+import (
+ "bd2server/internal/server/domain/battle/castle"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "slices"
+ "sort"
+ "sync"
+)
+
+type Castle struct {
+ store Store
+ writer sync.Mutex
+ mu sync.RWMutex
+ players map[uint64]castle.RankPublication
+ boards map[[2]uint64][]castle.RankEntry
+}
+
+func NewCastle(ctx context.Context, store Store) (*Castle, error) {
+ if store == nil {
+ return nil, errors.New("castle ranking requires persistence")
+ }
+ r := &Castle{store: store, players: map[uint64]castle.RankPublication{}, boards: map[[2]uint64][]castle.RankEntry{}}
+ e := store.View(ctx, func(tx Tx) error {
+ for cursor := ""; ; {
+ rows, e := tx.Scan("castle.players", "", cursor, 256)
+ if e != nil {
+ return e
+ }
+ if len(rows) == 0 {
+ return nil
+ }
+ for _, row := range rows {
+ var p castle.RankPublication
+ if e = json.Unmarshal(row.Value, &p); e != nil {
+ return e
+ }
+ if e = validCastlePublication(p); e != nil {
+ return e
+ }
+ if _, ok := r.players[p.Profile.Owner]; ok {
+ return errors.New("duplicate castle owner")
+ }
+ r.apply(p)
+ cursor = row.Key
+ }
+ }
+ })
+ return r, e
+}
+func validCastlePublication(p castle.RankPublication) error {
+ if p.Account == "" || p.Version == 0 || p.Profile.Owner == 0 {
+ return errors.New("invalid castle identity")
+ }
+ seen := map[[2]uint64]bool{}
+ for _, record := range p.Records {
+ key := [2]uint64{record.Season, record.Stage}
+ if record.Season == 0 || record.Point == 0 || seen[key] {
+ return errors.New("invalid castle record")
+ }
+ seen[key] = true
+ }
+ return nil
+}
+func compareCastle(a, b castle.RankEntry) int {
+ if a.Point != b.Point {
+ if a.Point > b.Point {
+ return -1
+ }
+ return 1
+ }
+ if a.Date != b.Date {
+ if a.Date < b.Date {
+ return -1
+ }
+ return 1
+ }
+ if a.Profile.Owner < b.Profile.Owner {
+ return -1
+ }
+ if a.Profile.Owner > b.Profile.Owner {
+ return 1
+ }
+ return 0
+}
+func (r *Castle) apply(p castle.RankPublication) {
+ for _, record := range p.Records {
+ key := [2]uint64{record.Season, record.Stage}
+ board := slices.DeleteFunc(r.boards[key], func(e castle.RankEntry) bool { return e.Profile.Owner == p.Profile.Owner })
+ entry := castle.RankEntry{RankRecord: record, Profile: p.Profile}
+ i := sort.Search(len(board), func(i int) bool { return compareCastle(board[i], entry) >= 0 })
+ r.boards[key] = slices.Insert(board, i, entry)
+ }
+ r.players[p.Profile.Owner] = p
+}
+func (r *Castle) Publish(ctx context.Context, p castle.RankPublication) error {
+ if e := validCastlePublication(p); e != nil {
+ return e
+ }
+ r.writer.Lock()
+ defer r.writer.Unlock()
+ r.mu.RLock()
+ old := r.players[p.Profile.Owner]
+ r.mu.RUnlock()
+ if old.Account != "" && old.Account != p.Account {
+ return errors.New("castle owner conflict")
+ }
+ if old.Version >= p.Version {
+ return nil
+ }
+ for _, previous := range old.Records {
+ found := false
+ for _, next := range p.Records {
+ if next.Season != previous.Season || next.Stage != previous.Stage {
+ continue
+ }
+ found = true
+ if next.Point < previous.Point {
+ return errors.New("castle score regressed")
+ }
+ }
+ if !found {
+ return errors.New("castle season lost")
+ }
+ }
+ raw, e := json.Marshal(p)
+ if e != nil {
+ return e
+ }
+ var owned castle.RankPublication
+ if e = json.Unmarshal(raw, &owned); e != nil {
+ return e
+ }
+ if e = r.store.Update(ctx, func(tx Tx) error { return tx.Put("castle.players", fmt.Sprintf("%020d", p.Profile.Owner), raw) }); e != nil {
+ return e
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.apply(owned)
+ return nil
+}
+func (r *Castle) Top(season, stage uint64, limit int) []castle.RankEntry {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ board := r.boards[[2]uint64{season, stage}]
+ out := make([]castle.RankEntry, min(max(limit, 0), len(board)))
+ for i := range out {
+ out[i] = board[i]
+ out[i].Rank = uint64(i + 1)
+ out[i].Profile.Guild = slices.Clone(out[i].Profile.Guild)
+ }
+ return out
+}
+func (r *Castle) Rank(owner uint64, record castle.RankRecord) castle.RankEntry {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ profile := r.players[owner].Profile
+ profile.Owner = owner
+ profile.Guild = slices.Clone(profile.Guild)
+ entry := castle.RankEntry{RankRecord: record, Profile: profile}
+ board := r.boards[[2]uint64{record.Season, record.Stage}]
+ rank := uint64(1)
+ for _, other := range board {
+ if other.Profile.Owner != owner && compareCastle(other, entry) < 0 {
+ rank++
+ }
+ }
+ entry.Rank = rank
+ return entry
+}
diff --git a/go/internal/server/domain/ranking/castle_test.go b/go/internal/server/domain/ranking/castle_test.go
new file mode 100644
index 0000000..55a73d1
--- /dev/null
+++ b/go/internal/server/domain/ranking/castle_test.go
@@ -0,0 +1,201 @@
+package ranking
+
+import (
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/battle"
+ "bd2server/internal/server/domain/battle/castle"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/shared"
+ "bd2server/internal/server/storage/stateio"
+ "context"
+ "fmt"
+ "testing"
+ "time"
+)
+
+// Synthetic rewards distinguish rank one from rank two. Both players earn
+// their scores through an ordinary encounter and boss before season rollover.
+func TestCastlePlayedSeasonRanksAndRewardsSurviveRestart(t *testing.T) {
+ ctx := context.Background()
+ directory := t.TempDir()
+ store, e := shared.Open(directory)
+ if e != nil {
+ t.Fatal(e)
+ }
+ ranks, e := NewCastle(ctx, testPVPStore{store})
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer func() {
+ if e := store.Close(); e != nil {
+ t.Error(e)
+ }
+ }()
+ season := uint64(1)
+ settled := false
+ now := time.Date(2026, 10, 18, 0, 0, 0, 0, time.UTC)
+ design := &gamedata.CastleRewardDesign{PackID: 31, Reset: gamedata.FieldResetSchedule{}, Floors: map[uint64]gamedata.CastleFloor{1: {ID: 1, Boss: 52, Monsters: map[uint64]uint64{51: 61, 52: 62}, Scoring: gamedata.CastleScoring{Base: 10, Turn: 100, BossMultiplier: 2}}}, Decks: map[uint64]gamedata.CastleDeck{61: {ID: 61}, 62: {ID: 62}}, Characters: map[uint64]gamedata.CastleCharacter{71: {Unique: 71}}, FloorRanks: []gamedata.CastleRankReward{{Rank: 1, Rewards: []gamedata.Reward{{Type: 4, Count: 3}}}, {Rank: 2, Rewards: []gamedata.Reward{{Type: 4, Count: 1}}}}, TotalRanks: []gamedata.CastleRankReward{{Rank: 1, Rewards: []gamedata.Reward{{Type: 4, Count: 8}}}, {Rank: 2, Rewards: []gamedata.Reward{{Type: 4, Count: 4}}}}}
+ request := func(seq uint64, fields ...uint64) []byte {
+ raw := wire.AppendVarint(nil, 1, seq)
+ for i, value := range fields {
+ raw = wire.AppendVarint(raw, i+2, value)
+ }
+ return raw
+ }
+ value := func(raw []byte, field int) uint64 { v, _, _ := wire.Varint(raw, field); return v }
+ messages := func(raw []byte, field int) [][]byte {
+ var rows [][]byte
+ if e := wire.Walk(raw, func(f wire.Field) error {
+ if f.Number == field {
+ rows = append(rows, f.Value)
+ }
+ return nil
+ }); e != nil {
+ t.Fatal(e)
+ }
+ return rows
+ }
+ accounts := []command.Context{{Identity: command.Identity{AccountID: "alice", SessionID: "alice"}, State: stateio.NewMemory()}, {Identity: command.Identity{AccountID: "bob", SessionID: "bob"}, State: stateio.NewMemory()}}
+ balance := func(c command.Context) uint64 {
+ raw, _, e := c.State.LoadEntry("inventory", "test_wallet", "gold")
+ if e != nil {
+ t.Fatal(e)
+ }
+ return value(raw, 1)
+ }
+ proof := battle.SettlementEvidence{}
+ open := func(owner uint64) *castle.Service {
+ s := castle.NewService(design)
+ s.AttachClock(func() time.Time { return now })
+ s.AttachPeriod(func(command.Context) (uint64, bool, error) { return season, !settled, nil })
+ s.AttachSeasonSettlement(func(id uint64) bool { return settled && id == 1 })
+ s.AttachCurrentPack(func(command.Context) (int, error) { return 31, nil })
+ s.AttachEvidence(func(command.Context) battle.SettlementEvidence { return proof })
+ s.AttachTotalWarValidation(func(_ command.Context, ps []castle.Participant) error {
+ for _, p := range ps {
+ if p.CharacterIndex != 81 || p.CharacterID != 71 {
+ return fmt.Errorf("not owned")
+ }
+ }
+ return nil
+ })
+ s.AttachRanking(owner, ranks)
+ s.AttachRewards(func(c command.Context, key string, rewards []gamedata.Reward) ([]byte, error) {
+ if _, ok, e := c.State.LoadEntry("inventory", "test_grants", key); e != nil || ok {
+ return nil, e
+ }
+ gold := balance(c)
+ for _, reward := range rewards {
+ if reward.Type != 4 {
+ return nil, fmt.Errorf("unsupported test currency")
+ }
+ gold += reward.Count
+ }
+ if e := c.State.PutEntry("inventory", "test_wallet", "gold", wire.AppendVarint(nil, 1, gold)); e != nil {
+ return nil, e
+ }
+ return nil, c.State.PutEntry("inventory", "test_grants", key, []byte("true"))
+ })
+ return s
+ }
+ execute := func(s *castle.Service, c command.Context, path string, body []byte) []byte {
+ _, out, handled, e := s.Handle(c, path, body)
+ if e != nil || !handled {
+ t.Fatalf("%s handled=%v: %v", path, handled, e)
+ }
+ return out
+ }
+ services := []*castle.Service{open(11), open(22)}
+ for i, s := range services {
+ c := accounts[i]
+ execute(s, c, "/EvilCastleEnter", request(1, 31, 1))
+ blue := wire.AppendVarint(nil, 2, 81)
+ blue = wire.AppendVarint(blue, 3, 71)
+ hero := wire.AppendVarint(nil, 1, 81)
+ hero = wire.AppendVarint(hero, 2, 71)
+ hero = wire.AppendVarint(hero, 3, 1)
+ for _, monster := range []uint64{51, 52} {
+ deck := design.Floors[1].Monsters[monster]
+ receipt := fmt.Sprintf("%s:%d", c.AccountID, monster)
+ if _, e := s.EnterBattle(c, request(monster, 0, monster, deck, 7), receipt); e != nil {
+ t.Fatal(e)
+ }
+ proof = battle.SettlementEvidence{Receipt: receipt, Mode: 7, Deck: deck, Monster: monster, Round: uint64(5 - i*4), InitialBlue: [][]byte{blue}}
+ if _, e := s.CompleteBattle(c, wire.AppendBytes(request(monster+100, 1), 3, hero), receipt); e != nil {
+ t.Fatal(e)
+ }
+ }
+ records, e := s.RankRecords(c)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = ranks.Publish(ctx, castle.RankPublication{Account: c.AccountID, Version: 1, Profile: castle.RankProfile{Owner: uint64(11 + i*11), Name: c.AccountID}, Records: records}); e != nil {
+ t.Fatal(e)
+ }
+ }
+ // Bob clears in one turn; Alice needs five, so Bob wins each floor and total.
+ for i, s := range services {
+ out := execute(s, accounts[i], "/EvilCastleRankingInfo", request(201, 31, 1, 1))
+ rows := messages(out, 1)
+ if len(rows) != 2 || value(rows[0], 1) != 22 || value(rows[1], 1) != 11 {
+ t.Fatal("played cross-account ranking order is wrong")
+ }
+ own := messages(out, 2)
+ if len(own) != 1 || value(own[0], 7) != uint64(2-i) {
+ t.Fatal("personal ranking differs from board")
+ }
+ stage := execute(s, accounts[i], "/EvilCastleStageRankingInfo", request(202, 31, 1, 1))
+ if value(stage, 1) != uint64(2-i) || value(stage, 3) != uint64(2-i) {
+ t.Fatal("stage and total rank disagree")
+ }
+ }
+ execute(services[0], accounts[0], "/EvilCastleRewardInfo", request(203, 31))
+ if balance(accounts[0]) != 0 {
+ t.Fatal("unsettled season paid rewards")
+ }
+ season = 2
+ settled = true
+ if e = store.Close(); e != nil {
+ t.Fatal(e)
+ }
+ store, e = shared.Open(directory)
+ if e != nil {
+ t.Fatal(e)
+ }
+ ranks, e = NewCastle(ctx, testPVPStore{store})
+ if e != nil {
+ t.Fatal(e)
+ }
+ for i, c := range accounts {
+ s := open(uint64(11 + i*11))
+ execute(s, c, "/EvilCastleInfo", request(204, 31))
+ history := execute(s, c, "/EvilCastleStageRankingInfo", request(205, 31, 1, 1))
+ if value(history, 1) != uint64(2-i) {
+ t.Fatal("season change or shared restart lost historical rank")
+ }
+ claim := request(206, 31)
+ out := execute(s, c, "/EvilCastleRewardInfo", claim)
+ floorRows, totalRows := messages(out, 1), messages(out, 2)
+ if len(floorRows) != 1 || len(totalRows) != 1 || value(floorRows[0], 1) != uint64(2-i) || value(totalRows[0], 1) != uint64(2-i) {
+ t.Fatal("season payout used wrong player's rank")
+ }
+ want := uint64(5)
+ if i == 1 {
+ want = 11
+ }
+ if balance(c) != want {
+ t.Fatalf("player %s credited %d, want %d", c.AccountID, balance(c), want)
+ }
+ execute(s, c, "/EvilCastleRewardInfo", claim)
+ s = open(uint64(11 + i*11))
+ execute(s, c, "/EvilCastleRewardInfo", request(207, 31))
+ if balance(c) != want {
+ t.Fatal("retry or reopen duplicated season payout")
+ }
+ info := execute(s, c, "/EvilCastleInfo", request(208, 31))
+ if len(messages(info, 1)) != 0 {
+ t.Fatal("old score leaked into next season")
+ }
+ }
+}
diff --git a/go/internal/server/domain/ranking/popularity.go b/go/internal/server/domain/ranking/popularity.go
new file mode 100644
index 0000000..6bfdd47
--- /dev/null
+++ b/go/internal/server/domain/ranking/popularity.go
@@ -0,0 +1,16 @@
+package ranking
+
+import "bd2server/internal/server/domain/battle/pvp"
+
+func (p *PVP) PopularityRank(snapshot pvp.PublishedSnapshot) (uint64, error) {
+ p.mu.RLock()
+ defer p.mu.RUnlock()
+ if board := p.boards[pvpBoardKey(snapshot.Mode, snapshot.Season)]; board != nil {
+ if row, ok := board.Members[snapshot.Profile.OwnerID]; ok {
+ snapshot.VP = p.score(row)
+ snapshot.Rank = p.rank(board, snapshot.Profile.OwnerID)
+ }
+ }
+ rank, e := p.design.MirrorRank(snapshot.Season, snapshot.VP, snapshot.Rank)
+ return rank.ID, e
+}
diff --git a/go/internal/server/domain/ranking/roguelike.go b/go/internal/server/domain/ranking/roguelike.go
new file mode 100644
index 0000000..0811a3e
--- /dev/null
+++ b/go/internal/server/domain/ranking/roguelike.go
@@ -0,0 +1,190 @@
+package ranking
+
+import (
+ "bd2server/internal/server/domain/battle/roguelike"
+ "bd2server/internal/server/domain/command"
+ "context"
+ "encoding/json"
+ "fmt"
+ "math"
+ "slices"
+ "sort"
+ "sync"
+)
+
+type RogueLike struct {
+ store Store
+ writer sync.Mutex
+ mu sync.RWMutex
+ records map[[2]uint64]roguelike.RankPublication
+ boards map[uint64][]roguelike.RankEntry
+ totals map[uint64]uint64
+}
+
+func NewRogueLike(ctx context.Context, store Store) (*RogueLike, error) {
+ if store == nil {
+ return nil, fmt.Errorf("roguelike ranking: missing store")
+ }
+ r := &RogueLike{store: store, records: map[[2]uint64]roguelike.RankPublication{}, boards: map[uint64][]roguelike.RankEntry{}, totals: map[uint64]uint64{}}
+ e := store.View(ctx, func(tx Tx) error {
+ for cursor := ""; ; {
+ rows, e := tx.Scan("roguelike.players", "", cursor, 256)
+ if e != nil {
+ return e
+ }
+ for _, row := range rows {
+ var p roguelike.RankPublication
+ if e = json.Unmarshal(row.Value, &p); e != nil {
+ return e
+ }
+ if e = validateRogue(p); e != nil {
+ return e
+ }
+ r.apply(p)
+ cursor = row.Key
+ }
+ if len(rows) < 256 {
+ return nil
+ }
+ }
+ })
+ return r, e
+}
+func validateRogue(p roguelike.RankPublication) error {
+ if p.Account == "" || p.Season == 0 || p.Version == 0 || p.Entry.Owner == 0 || p.Entry.Score > math.MaxInt64 || p.Entry.Damage > math.MaxInt64 {
+ return fmt.Errorf("roguelike ranking: invalid publication")
+ }
+ return nil
+}
+func compareRogue(a, b roguelike.RankEntry) int {
+ if a.Damage > b.Damage {
+ return -1
+ }
+ if a.Damage < b.Damage {
+ return 1
+ }
+ if a.Score > b.Score {
+ return -1
+ }
+ if a.Score < b.Score {
+ return 1
+ }
+ if a.Owner < b.Owner {
+ return -1
+ }
+ if a.Owner > b.Owner {
+ return 1
+ }
+ return 0
+}
+func (r *RogueLike) apply(p roguelike.RankPublication) {
+ key := [2]uint64{p.Season, p.Entry.Owner}
+ prior := r.records[key]
+ r.totals[p.Season] = r.totals[p.Season] - prior.Entry.Score + p.Entry.Score
+ board := slices.DeleteFunc(r.boards[p.Season], func(e roguelike.RankEntry) bool { return e.Owner == p.Entry.Owner })
+ at := sort.Search(len(board), func(i int) bool { return compareRogue(board[i], p.Entry) >= 0 })
+ r.boards[p.Season] = slices.Insert(board, at, p.Entry)
+ r.records[key] = p
+}
+func (r *RogueLike) Publish(ctx context.Context, p roguelike.RankPublication) error {
+ if e := validateRogue(p); e != nil {
+ return e
+ }
+ r.writer.Lock()
+ defer r.writer.Unlock()
+ r.mu.RLock()
+ old := r.records[[2]uint64{p.Season, p.Entry.Owner}]
+ total := r.totals[p.Season]
+ r.mu.RUnlock()
+ if old.Account != "" && old.Account != p.Account {
+ return fmt.Errorf("roguelike ranking: owner conflict")
+ }
+ if old.Version >= p.Version {
+ return nil
+ }
+ if p.Entry.Score < old.Entry.Score || p.Entry.Damage < old.Entry.Damage || p.Entry.Score-old.Entry.Score > math.MaxInt64-total {
+ return fmt.Errorf("roguelike ranking: regressed or overflowed score")
+ }
+ raw, e := json.Marshal(p)
+ if e != nil {
+ return e
+ }
+ var owned roguelike.RankPublication
+ if e = json.Unmarshal(raw, &owned); e != nil {
+ return e
+ }
+ if e = r.store.Update(ctx, func(tx Tx) error {
+ return tx.Put("roguelike.players", fmt.Sprintf("%020d:%020d", p.Season, p.Entry.Owner), raw)
+ }); e != nil {
+ return e
+ }
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.apply(owned)
+ return nil
+}
+func (r *RogueLike) Total(_ command.Context, season uint64) (uint64, error) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ return r.totals[season], nil
+}
+func (r *RogueLike) Snapshot(_ command.Context, season uint64, local roguelike.RankEntry) ([]roguelike.RankEntry, roguelike.RankEntry, error) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ board := r.boards[season]
+ prior := r.records[[2]uint64{season, local.Owner}].Entry
+ if prior.Score > local.Score {
+ local.Score = prior.Score
+ }
+ if prior.Damage > local.Damage {
+ local.Damage = prior.Damage
+ }
+ local.Profile = slices.Clone(prior.Profile)
+ at := sort.Search(len(board), func(i int) bool { return compareRogue(board[i], local) >= 0 })
+ rank := at + 1
+ if compareRogue(prior, local) < 0 {
+ rank--
+ }
+ local.Rank = uint64(max(rank, 1))
+ if local.Score == 0 {
+ local.Rank = 0
+ }
+ top := make([]roguelike.RankEntry, 0, min(100, len(board)+1))
+ inserted := false
+ for _, e := range board {
+ if e.Owner == local.Owner {
+ continue
+ }
+ if !inserted && local.Score > 0 && compareRogue(local, e) < 0 {
+ top = append(top, local)
+ inserted = true
+ }
+ if len(top) >= 100 {
+ break
+ }
+ e.Profile = slices.Clone(e.Profile)
+ top = append(top, e)
+ }
+ if !inserted && local.Score > 0 && len(top) < 100 {
+ top = append(top, local)
+ }
+ for i := range top {
+ top[i].Rank = uint64(i + 1)
+ }
+ return top, local, nil
+}
+
+func (r *RogueLike) PendingTotal(_ command.Context, season uint64, local roguelike.RankEntry) (uint64, error) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+ total := r.totals[season]
+ previous := r.records[[2]uint64{season, local.Owner}].Entry.Score
+ if local.Score <= previous {
+ return total, nil
+ }
+ delta := local.Score - previous
+ if delta > math.MaxInt64-total {
+ return 0, fmt.Errorf("roguelike ranking: pending total overflow")
+ }
+ return total + delta, nil
+}
diff --git a/go/internal/server/domain/ranking/roguelike_test.go b/go/internal/server/domain/ranking/roguelike_test.go
new file mode 100644
index 0000000..4fcd627
--- /dev/null
+++ b/go/internal/server/domain/ranking/roguelike_test.go
@@ -0,0 +1,84 @@
+package ranking
+
+import (
+ "bd2server/internal/server/domain/battle/roguelike"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/storage/shared"
+ "context"
+ "testing"
+)
+
+func TestRogueLikeCachedScoresRetryReopenAndPendingOwnRank(t *testing.T) {
+ ctx := context.Background()
+ dir := t.TempDir()
+ store, e := shared.Open(dir)
+ if e != nil {
+ t.Fatal(e)
+ }
+ defer func() { _ = store.Close() }()
+ rank, e := NewRogueLike(ctx, testPVPStore{store})
+ if e != nil {
+ t.Fatal(e)
+ }
+ alice := roguelike.RankPublication{Account: "alice", Season: 1, Version: 1, Entry: roguelike.RankEntry{Owner: 1, Score: 600, Damage: 20}}
+ bob := roguelike.RankPublication{Account: "bob", Season: 1, Version: 1, Entry: roguelike.RankEntry{Owner: 2, Score: 400, Damage: 10}}
+ for _, p := range []roguelike.RankPublication{alice, bob, alice} {
+ if e = rank.Publish(ctx, p); e != nil {
+ t.Fatal(e)
+ }
+ }
+ total, e := rank.Total(command.Context{}, 1)
+ if e != nil || total != 1000 {
+ t.Fatalf("duplicate delivery changed contribution: %d %v", total, e)
+ }
+ pendingTotal, e := rank.PendingTotal(command.Context{}, 1, roguelike.RankEntry{Owner: 2, Score: 700})
+ if e != nil || pendingTotal != 1300 {
+ t.Fatal("own committed settlement was omitted before projection delivery")
+ }
+ pending := bob.Entry
+ pending.Damage = 30
+ top, mine, e := rank.Snapshot(command.Context{}, 1, pending)
+ if e != nil || len(top) != 2 || top[0].Owner != 2 || mine.Rank != 1 {
+ t.Fatalf("pending own record did not overlay board: %+v %+v %v", top, mine, e)
+ }
+ top[0].Score = 99
+ again, _, _ := rank.Snapshot(command.Context{}, 1, alice.Entry)
+ if again[0].Owner != 1 {
+ t.Fatal("local unpublished overlay mutated shared board")
+ }
+ bob.Version++
+ bob.Entry.Damage = 30
+ bob.Entry.Score = 700
+ if e = rank.Publish(ctx, bob); e != nil {
+ t.Fatal(e)
+ }
+ total, _ = rank.Total(command.Context{}, 1)
+ if total != 1300 {
+ t.Fatal("improvement counted the owner's whole score again")
+ }
+ if e = store.Close(); e != nil {
+ t.Fatal(e)
+ }
+ store, e = shared.Open(dir)
+ if e != nil {
+ t.Fatal(e)
+ }
+ rank, e = NewRogueLike(ctx, testPVPStore{store})
+ if e != nil {
+ t.Fatal(e)
+ }
+ total, _ = rank.Total(command.Context{}, 1)
+ top, mine, e = rank.Snapshot(command.Context{}, 1, alice.Entry)
+ if e != nil || total != 1300 || len(top) != 2 || top[0].Owner != 2 || mine.Rank != 2 {
+ t.Fatal("restored score sum or board lost committed results")
+ }
+ empty, _ := rank.Total(command.Context{}, 2)
+ if empty != 0 {
+ t.Fatal("ranking total leaked into next season")
+ }
+ bob.Version++
+ bob.Entry.Score = 100
+ if e = rank.Publish(ctx, bob); e == nil {
+ t.Fatal("accepted regressed contribution")
+ }
+}
diff --git a/go/internal/server/domain/roster/collection.go b/go/internal/server/domain/roster/collection.go
index 6f3e3c0..71bee96 100644
--- a/go/internal/server/domain/roster/collection.go
+++ b/go/internal/server/domain/roster/collection.go
@@ -266,7 +266,7 @@ func (s *CollectionStore) CompleteStepUp(ctx command.Context, groupID, step uint
}
func (s *CollectionStore) SaveGachaSelections(ctx command.Context, groupID uint64, selections []GachaSelection, changeLimit uint64) error {
- if groupID == 0 || len(selections) == 0 {
+ if groupID == 0 {
return errors.New("player: invalid gacha selection")
}
@@ -276,12 +276,16 @@ func (s *CollectionStore) SaveGachaSelections(ctx command.Context, groupID uint6
if equalGachaSelections(s.data.GachaSelections[key], normalized) {
return nil
}
- if changeLimit != 0 && s.data.GachaSelectionChanges[key] >= changeLimit {
+ if len(normalized) != 0 && changeLimit != 0 && s.data.GachaSelectionChanges[key] >= changeLimit {
return fmt.Errorf("player: gacha selection group %d exhausted %d changes", groupID, changeLimit)
}
next := cloneCollection(s.data)
- next.GachaSelections[key] = normalized
- if changeLimit != 0 {
+ if len(normalized) == 0 {
+ delete(next.GachaSelections, key)
+ } else {
+ next.GachaSelections[key] = normalized
+ }
+ if len(normalized) != 0 && changeLimit != 0 {
next.GachaSelectionChanges[key]++
}
return s.commit(ctx, next)
@@ -598,7 +602,6 @@ func (s *CollectionStore) grantCostumesSorted(ctx command.Context, identity stri
return CollectionGrant{}, err
}
grant.Exchanges = append(grant.Exchanges, exchange)
- grant.Upgrades = append(grant.Upgrades, CostumeUpgrade{InvenIndex: exchange.InvenIndex, CostumeID: costumeID, Before: maxLevel, After: maxLevel, SortID: exchange.SortID})
}
continue
}
@@ -614,7 +617,6 @@ func (s *CollectionStore) grantCostumesSorted(ctx command.Context, identity stri
return CollectionGrant{}, err
}
grant.Exchanges = append(grant.Exchanges, exchange)
- grant.Upgrades = append(grant.Upgrades, CostumeUpgrade{InvenIndex: exchange.InvenIndex, CostumeID: costumeID, Before: maxLevel, After: maxLevel, SortID: exchange.SortID})
}
continue
}
diff --git a/go/internal/server/domain/roster/collection_entries.go b/go/internal/server/domain/roster/collection_entries.go
index 2a4b073..db82460 100644
--- a/go/internal/server/domain/roster/collection_entries.go
+++ b/go/internal/server/domain/roster/collection_entries.go
@@ -17,6 +17,7 @@ const collectionDomain = "collection"
var collectionEntryBuckets = [...]string{
"characters", "costumes", "grants", "gacha_applied", "gacha_users",
"gacha_fixed", "step_up_progress", "gacha_point_exchanges",
+ "gacha_history", "gacha_history_receipts", "gacha_history_clock", "gacha_history_totals",
"gacha_selections", "gacha_selection_changes", "costume_potential",
"costume_burst_levels", "costume_burst_upgrades", "char_awake", "char_partners", "costume_potential_locks", "friendships",
}
diff --git a/go/internal/server/domain/roster/deck/deck.go b/go/internal/server/domain/roster/deck/deck.go
index e115965..c98fa8b 100644
--- a/go/internal/server/domain/roster/deck/deck.go
+++ b/go/internal/server/domain/roster/deck/deck.go
@@ -80,6 +80,7 @@ type Store struct {
replies map[string]deckReply
waypointDesign func(uint64) (gamedata.WaypointPack, error)
waypointPack func(ctx command.Context, _ uint64, _ bool) error
+ waypointTalent func(ctx command.Context, pack, mapID, seq uint64) error
}
type deckReply struct {
diff --git a/go/internal/server/domain/roster/deck/protocol_adapter.go b/go/internal/server/domain/roster/deck/protocol_adapter.go
index 6567bba..530605e 100644
--- a/go/internal/server/domain/roster/deck/protocol_adapter.go
+++ b/go/internal/server/domain/roster/deck/protocol_adapter.go
@@ -199,17 +199,25 @@ func (s *Store) handleWaypoint(ctx command.Context, path string, req []byte) (in
return 0, nil, true, errors.New("deck: invalid waypoint destination")
}
target, known := design.Points[end]
- if !known || target.MapID == 0 || !hasWaypoint(s.state.Waypoints[pack], end) || !hasWaypoint(s.state.Waypoints[pack], id) {
+ talent := design.Points[id].MapID == 0
+ if !known || target.MapID == 0 || !hasWaypoint(s.state.Waypoints[pack], end) || !talent && !hasWaypoint(s.state.Waypoints[pack], id) {
return 0, nil, true, errors.New("deck: waypoint is not activated")
}
moves, found, err := wire.Varint(req, 5)
if err != nil || !found || moves != 1 {
return 0, nil, true, errors.New("deck: invalid waypoint move count")
}
- if reply, ok := s.cachedReplyLocked(ctx, "waypoint-use", seq); ok {
+ if talent {
+ if s.waypointTalent == nil {
+ return 0, nil, true, errors.New("deck: waypoint talent authorization unavailable")
+ }
+ if err := s.waypointTalent(ctx, pack, target.MapID, seq); err != nil {
+ return 0, nil, true, err
+ }
+ } else if reply, ok := s.cachedReplyLocked(ctx, "waypoint-use", seq); ok {
return reply.code, reply.body, true, nil
}
- if design.PriceUnit != 0 {
+ if !talent && design.PriceUnit != 0 {
if s.wallet == nil || ctx.SessionID == "" {
return 0, nil, true, errors.New("deck: waypoint wallet session unavailable")
}
diff --git a/go/internal/server/domain/roster/deck/recommendation.go b/go/internal/server/domain/roster/deck/recommendation.go
index fdaa655..1147c96 100644
--- a/go/internal/server/domain/roster/deck/recommendation.go
+++ b/go/internal/server/domain/roster/deck/recommendation.go
@@ -11,6 +11,7 @@ import (
"fmt"
"math"
"slices"
+ "time"
)
type RecommendContext struct{ BattleMode, PackID, BattleIndex, Level, TeamCountType, DeckType uint64 }
@@ -191,6 +192,13 @@ func (s *Store) PrepareRecommendationSnapshot(ctx command.Context, identity stri
}
const RecommendationTopic = "deck.recommendation"
+const PopularityTopic = "deck.popularity"
+
+type PopularityPublication struct {
+ CompletedAt, Score, OwnerIndex uint64
+ TotalWarCostumes []uint64
+ Record RecommendRecord
+}
type RecommendationPublication struct {
Revision uint64
@@ -258,6 +266,25 @@ func (s *Store) CompleteRecommendation(ctx command.Context, identity string, win
if e != nil {
return e
}
+ if found && options.IsSave {
+ var record RecommendRecord
+ if e = json.Unmarshal(raw, &record); e != nil {
+ return e
+ }
+ if e = record.Validate(); e != nil {
+ return e
+ }
+ switch record.Context.BattleMode {
+ case 7, 16, 19, 20:
+ payload, err := json.Marshal(PopularityPublication{CompletedAt: uint64(time.Now().UnixMilli()), Record: record})
+ if err != nil {
+ return err
+ }
+ if e = ctx.Publish(command.Event{ID: "battle:" + identity, Topic: PopularityTopic, Payload: payload}); e != nil {
+ return e
+ }
+ }
+ }
if found && win && options.IsSave {
var record RecommendRecord
if json.Unmarshal(raw, &record) != nil {
diff --git a/go/internal/server/domain/roster/deck/waypoint.go b/go/internal/server/domain/roster/deck/waypoint.go
index 62a75e0..f611110 100644
--- a/go/internal/server/domain/roster/deck/waypoint.go
+++ b/go/internal/server/domain/roster/deck/waypoint.go
@@ -23,6 +23,10 @@ func (s *Store) ActivatedWaypoint(pack, id uint64) bool {
return hasWaypoint(s.state.Waypoints[pack], id)
}
+func (s *Store) AttachWaypointTalent(consume func(ctx command.Context, pack, mapID, seq uint64) error) {
+ s.waypointTalent = consume
+}
+
func (s *Store) ActivatedWaypointCount() uint64 {
var count uint64
for _, points := range s.state.Waypoints {
diff --git a/go/internal/server/domain/roster/friendship.go b/go/internal/server/domain/roster/friendship.go
index e20134c..0622ca9 100644
--- a/go/internal/server/domain/roster/friendship.go
+++ b/go/internal/server/domain/roster/friendship.go
@@ -2,6 +2,7 @@ package roster
import (
"bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
assets "bd2server/internal/server/domain/inventory"
"errors"
@@ -10,6 +11,11 @@ import (
"time"
)
+type FriendshipEconomy interface {
+ CurrencyBalance(command.Context, uint64) (uint64, error)
+ Apply(command.Context, string, []gamedata.Reward, []gamedata.Reward) ([]byte, error)
+}
+
// FriendshipService applies inventory gifts and counseling inside the account
// request transaction. Static IDs, thresholds and rewards come from GameData.
type FriendshipService struct {
@@ -18,16 +24,20 @@ type FriendshipService struct {
potential *gamedata.CostumePotentialDesign
collection *CollectionStore
inventory *assets.Inventory
- wallet *assets.Wallet
+ economy FriendshipEconomy
now func() time.Time
}
-func NewFriendshipService(design *gamedata.FriendshipDesign, awake *gamedata.CharAwakeDesign, potential *gamedata.CostumePotentialDesign, collection *CollectionStore, inventory *assets.Inventory, wallet *assets.Wallet) (*FriendshipService, error) {
- if design == nil || awake == nil || potential == nil || collection == nil || inventory == nil || wallet == nil {
+func (s *FriendshipService) AttachEconomy(economy FriendshipEconomy) {
+ s.economy = economy
+}
+
+func NewFriendshipService(design *gamedata.FriendshipDesign, awake *gamedata.CharAwakeDesign, potential *gamedata.CostumePotentialDesign, collection *CollectionStore, inventory *assets.Inventory) (*FriendshipService, error) {
+ if design == nil || awake == nil || potential == nil || collection == nil || inventory == nil {
return nil, errors.New("player: incomplete friendship service")
}
- s := &FriendshipService{design: design, awake: awake, potential: potential, collection: collection, inventory: inventory, wallet: wallet, now: time.Now}
+ s := &FriendshipService{design: design, awake: awake, potential: potential, collection: collection, inventory: inventory, now: time.Now}
for _, entry := range collection.FriendshipEntries() {
if entry.Daily != nil && entry.Daily.Used > design.Default.MaxCounselingAP {
return nil, errors.New("player: saved daily friendship AP exceeds maximum")
@@ -64,6 +74,16 @@ func (s *FriendshipService) FriendshipAP() (uint64, error) {
return s.design.Default.MaxCounselingAP - daily.Used, nil
}
+func (s *FriendshipService) CurrentLevel(id uint64) uint64 {
+ if _, owned := s.owned(id); !owned {
+ return 0
+ }
+ if entry := s.collection.data.Friendships[friendshipStateKey(id)]; entry.State != nil {
+ return entry.State.Level
+ }
+ return 1
+}
+
func (s *FriendshipService) daily(entries map[string]FriendshipEntry, day string) FriendshipDaily {
if entry := entries["daily"]; entry.Daily != nil && entry.Daily.Day == day {
return *entry.Daily
diff --git a/go/internal/server/domain/roster/gacha_history.go b/go/internal/server/domain/roster/gacha_history.go
new file mode 100644
index 0000000..1f1d0f9
--- /dev/null
+++ b/go/internal/server/domain/roster/gacha_history.go
@@ -0,0 +1,150 @@
+package roster
+
+import (
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+ "encoding/json"
+ "fmt"
+ "math"
+ "slices"
+)
+
+type GachaHistoryEntry struct {
+ Time uint64
+ Body []byte
+}
+
+// RecordGachaHistory shares the account transaction with the draw receipt.
+func (s *CollectionStore) RecordGachaHistory(ctx command.Context, identity string, at uint64, body []byte, counts [4][13]uint64) error {
+ if identity == "" || at == 0 || at >= math.MaxInt64 || len(body) == 0 {
+ return fmt.Errorf("gacha: invalid history receipt")
+ }
+ if _, found, e := s.store.LoadEntry(ctx.State, collectionDomain, "gacha_history_receipts", identity); e != nil || found {
+ return e
+ }
+ raw, found, e := s.store.LoadEntry(ctx.State, collectionDomain, "gacha_history_clock", "latest")
+ if e != nil {
+ return e
+ }
+ var latest uint64
+ if found && json.Unmarshal(raw, &latest) != nil {
+ return fmt.Errorf("gacha: invalid history clock")
+ }
+ if at <= latest {
+ at = latest + 1
+ }
+ if at >= math.MaxInt64 {
+ return fmt.Errorf("gacha: history clock overflow")
+ }
+ totals, e := s.gachaHistoryTotals(ctx)
+ if e != nil {
+ return e
+ }
+ for kind := range totals {
+ for field := range totals[kind] {
+ n := counts[kind][field]
+ if n > math.MaxInt32-totals[kind][field] {
+ return fmt.Errorf("gacha: total count overflow")
+ }
+ totals[kind][field] += n
+ }
+ }
+ entry := GachaHistoryEntry{Time: at, Body: wire.AppendVarint(append([]byte(nil), body...), 13, at)}
+ payload, e := json.Marshal(entry)
+ if e != nil {
+ return e
+ }
+ clock, e := json.Marshal(at)
+ if e != nil {
+ return e
+ }
+ summary, e := json.Marshal(totals)
+ if e != nil {
+ return e
+ }
+ key := fmt.Sprintf("%020d", at)
+ return s.store.SaveWithEntries(ctx.State, collectionDomain, nil, []stateio.EntryMutation{{Bucket: "gacha_history", Key: key, Payload: payload}, {Bucket: "gacha_history_receipts", Key: identity, Payload: clock}, {Bucket: "gacha_history_clock", Key: "latest", Payload: clock}, {Bucket: "gacha_history_totals", Key: "all", Payload: summary}})
+}
+
+func (s *CollectionStore) gachaHistoryTotals(ctx command.Context) ([4][13]uint64, error) {
+ var totals [4][13]uint64
+ raw, found, e := s.store.LoadEntry(ctx.State, collectionDomain, "gacha_history_totals", "all")
+ if e != nil {
+ return totals, e
+ }
+ if found && json.Unmarshal(raw, &totals) != nil {
+ return totals, fmt.Errorf("gacha: invalid history total")
+ }
+ return totals, nil
+}
+
+func (s *CollectionStore) GachaHistory(ctx command.Context, after uint64) ([]byte, error) {
+ var entries []GachaHistoryEntry
+ read := func(key string, raw []byte) error {
+ var v GachaHistoryEntry
+ if json.Unmarshal(raw, &v) != nil || v.Time == 0 || len(v.Body) == 0 || key != fmt.Sprintf("%020d", v.Time) {
+ return fmt.Errorf("gacha: invalid saved history")
+ }
+ if v.Time > after {
+ entries = append(entries, v)
+ }
+ return nil
+ }
+ if pager, ok := ctx.State.(interface {
+ EntryPrefixPage(string, string, string, string, int) ([]stateio.Entry, error)
+ }); ok {
+ for cursor := fmt.Sprintf("%020d", after); ; {
+ rows, e := pager.EntryPrefixPage(collectionDomain, "gacha_history", "", cursor, 256)
+ if e != nil {
+ return nil, e
+ }
+ if len(rows) == 0 {
+ break
+ }
+ for _, row := range rows {
+ cursor = row.Key
+ if e = read(row.Key, row.Payload); e != nil {
+ return nil, e
+ }
+ }
+ }
+ } else {
+ rows, e := s.store.ListEntries(ctx.State, collectionDomain, "gacha_history")
+ if e != nil {
+ return nil, e
+ }
+ for key, raw := range rows {
+ if e = read(key, raw); e != nil {
+ return nil, e
+ }
+ }
+ }
+ slices.SortFunc(entries, func(a, b GachaHistoryEntry) int {
+ if a.Time < b.Time {
+ return 1
+ }
+ if a.Time > b.Time {
+ return -1
+ }
+ return 0
+ })
+ var body []byte
+ for _, entry := range entries {
+ body = wire.AppendBytes(body, 1, entry.Body)
+ }
+ totals, e := s.gachaHistoryTotals(ctx)
+ if e != nil {
+ return nil, e
+ }
+ for kind, counts := range totals {
+ v := wire.AppendVarint(nil, 1, uint64(kind))
+ for i, n := range counts {
+ if n != 0 {
+ v = wire.AppendVarint(v, i+2, n)
+ }
+ }
+ body = wire.AppendBytes(body, 2, v)
+ }
+ return body, nil
+}
diff --git a/go/internal/server/domain/roster/growth.go b/go/internal/server/domain/roster/growth.go
index e6d93fb..314dd5d 100644
--- a/go/internal/server/domain/roster/growth.go
+++ b/go/internal/server/domain/roster/growth.go
@@ -40,8 +40,9 @@ type CharacterStore struct {
immortal *gamedata.ImmortalDesign
immortalReplies map[string]talentUpgradeReply
- talentReplies map[string]map[string]talentUpgradeReply
- talentApplied map[string]talentUpgradeReply
+ talentReplies map[string]map[string]talentUpgradeReply
+ talentApplied map[string]talentUpgradeReply
+ talentUpgraded func(command.Context, Character) error
}
type talentUpgradeReply struct {
diff --git a/go/internal/server/domain/roster/protocol_costume_adapter.go b/go/internal/server/domain/roster/protocol_costume_adapter.go
index 22393b7..9a497c4 100644
--- a/go/internal/server/domain/roster/protocol_costume_adapter.go
+++ b/go/internal/server/domain/roster/protocol_costume_adapter.go
@@ -812,9 +812,20 @@ func (s *FriendshipService) counsel(ctx command.Context, request []byte, state F
day := now.UTC().Format("2006-01-02")
daily := s.daily(entries, day)
free := state.Level >= s.design.Default.MaxLevels[2]
+ var stacked bool
if !free {
if daily.Used >= s.design.Default.MaxCounselingAP {
- return nil, errors.New("player: no daily friendship AP remaining")
+ if s.economy == nil {
+ return nil, errors.New("player: no friendship AP remaining")
+ }
+ balance, err := s.economy.CurrencyBalance(ctx, 72)
+ if err != nil {
+ return nil, err
+ }
+ if balance == 0 {
+ return nil, errors.New("player: no friendship AP remaining")
+ }
+ stacked = true
}
if state.CounselingDay == day && state.CounselingCount >= s.design.Default.MaxCounselingAPByCostume {
return nil, errors.New("player: costume daily counseling limit reached")
@@ -835,7 +846,9 @@ func (s *FriendshipService) counsel(ctx command.Context, request []byte, state F
completed := slices.Contains(state.Sessions, session)
if !free {
rewards = append(rewards, s.design.Default.CounselingRewards...)
- daily.Used++
+ if !stacked {
+ daily.Used++
+ }
} else if !completed && quick == 0 {
// At the final cap the client allows unrestricted story playback. A
// previously unseen story earns its default reward once; repeated
@@ -857,7 +870,12 @@ func (s *FriendshipService) counsel(ctx command.Context, request []byte, state F
slices.Sort(next.Sessions)
}
}
- bundle, err := s.grant(ctx, key, rewards)
+ var bundle []byte
+ if stacked {
+ bundle, err = s.economy.Apply(ctx, key, []gamedata.Reward{{Type: 72, Count: 1}}, rewards)
+ } else {
+ bundle, err = s.grant(ctx, key, rewards)
+ }
if err != nil {
return nil, err
}
@@ -876,43 +894,10 @@ func (s *FriendshipService) counsel(ctx command.Context, request []byte, state F
}
func (s *FriendshipService) grant(ctx command.Context, identity string, rewards []gamedata.Reward) ([]byte, error) {
- if len(rewards) == 0 {
- return nil, nil
+ if s.economy == nil {
+ return nil, errors.New("player: friendship economy unavailable")
}
- var items []gamedata.BattleReward
- for _, reward := range rewards {
- if reward.Type == 0 || reward.Count == 0 || reward.Count > math.MaxInt32 {
- return nil, errors.New("player: invalid friendship reward")
- }
- switch reward.Type {
- case 2, 3, 4, 12, 20:
- default:
- if reward.ID == 0 || reward.ID > math.MaxInt32 {
- return nil, errors.New("player: invalid friendship item reward")
- }
- items = append(items, gamedata.BattleReward{Type: reward.Type, ID: reward.ID, Count: reward.Count}) //nolint:staticcheck // S1016
- }
- }
- if _, err := s.wallet.GrantQuestOnce(ctx, identity+":currency", rewards); err != nil {
- return nil, err
- }
- granted, err := s.inventory.GrantOnce(ctx, identity+":items", items)
- if err != nil {
- return nil, err
- }
- var bundle []byte
- for _, item := range granted {
- bundle = wire.AppendBytes(bundle, 1, assets.ItemWire(item))
- }
- for _, reward := range rewards {
- view := assets.Item{ID: reward.ID, Type: reward.Type, Count: reward.Count}
- bundle = wire.AppendBytes(bundle, 6, assets.ItemWire(view))
- switch reward.Type {
- case 2, 3, 4, 12, 20:
- bundle = wire.AppendBytes(bundle, 1, assets.ItemWire(view))
- }
- }
- return bundle, nil
+ return s.economy.Apply(ctx, identity, nil, rewards)
}
func (s *CostumePotentialService) connect(ctx command.Context, request []byte) (int, []byte, bool, error) {
diff --git a/go/internal/server/domain/roster/protocol_talent_adapter.go b/go/internal/server/domain/roster/protocol_talent_adapter.go
index 1d3e9e7..7199834 100644
--- a/go/internal/server/domain/roster/protocol_talent_adapter.go
+++ b/go/internal/server/domain/roster/protocol_talent_adapter.go
@@ -1,12 +1,12 @@
package roster
import (
+ "bd2server/internal/common/util"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
assets "bd2server/internal/server/domain/inventory"
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/stateio"
- "crypto/rand"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
@@ -14,7 +14,6 @@ import (
"errors"
"fmt"
"math"
- "math/big"
"slices"
"sort"
"strconv"
@@ -96,7 +95,7 @@ func (s *TalentUseService) Handle(ctx command.Context, path string, request []by
} else {
var owned bool
character, owned = s.characters.Find(ctx, index)
- if !owned || character.TalentLevel == 0 {
+ if !owned || character.TalentLevel == 0 || character.HP == 0 {
return fail(fmt.Errorf("player: talent caster unavailable"))
}
var exists bool
@@ -109,6 +108,9 @@ func (s *TalentUseService) Handle(ctx command.Context, path string, request []by
if !ok {
return fail(fmt.Errorf("player: talent level design unavailable"))
}
+ fail = func(e error) (int, []byte, bool, error) {
+ return 43, nil, true, fmt.Errorf("player: talent caster=%d character=%d group=%d class=%d level=%d target_count=%d targets=%v: %w", index, character.ID, rule.Group, rule.Class, rule.Level, len(targets), targets[:min(len(targets), 5)], e)
+ }
if s.context == nil {
return fail(fmt.Errorf("player: talent field context unavailable"))
}
@@ -185,11 +187,11 @@ func (s *TalentUseService) Handle(ctx command.Context, path string, request []by
if len(rule.Values) > 0 {
probability = rule.Values[0]
}
- draw, e := rand.Int(rand.Reader, big.NewInt(1000000))
+ draw, e := util.RandomUint64N(1000000)
if e != nil {
return fail(e)
}
- success = float64(draw.Int64()) < probability*10000
+ success = float64(draw) < probability*10000
}
if success && npc.Rewards[matched] > 0 {
rewards, ok := s.design.Rewards[npc.Rewards[matched]]
@@ -244,7 +246,7 @@ func (s *TalentUseService) Handle(ctx command.Context, path string, request []by
if err != nil {
return fail(err)
}
- } else if rule.Class == 4 || rule.Class == 18 || rule.Class == 20 {
+ } else if rule.Class == 4 || rule.Class == 15 || rule.Class == 18 || rule.Class == 20 {
return fail(fmt.Errorf("player: field talent executor unavailable"))
} else if len(targets) > 0 && rule.Class != 3 && rule.Class != 11 {
return fail(fmt.Errorf("player: unexpected talent targets"))
@@ -288,6 +290,9 @@ func (s *TalentUseService) Handle(ctx command.Context, path string, request []by
current.End += int64(rule.Values[1]) * 1000
}
state.Skills[rule.Group] = current
+ if rule.Class == 15 {
+ state.Receipts["waypoint:pending:"+ctx.SessionID] = talentUseReceipt{Digest: fmt.Sprintf("%d/%d", pack, targets[0])}
+ }
out := append([]byte(nil), extra...)
out = wire.AppendBytes(out, 1, talentUseWire(rule.Group, current, rule))
if gain > 0 {
@@ -838,6 +843,11 @@ func (s *CharacterStore) talentSkillUpgrade(ctx command.Context, request []byte)
}
s.characters = next
}
+ if s.talentUpgraded != nil {
+ if err := s.talentUpgraded(ctx, current); err != nil {
+ return 0, nil, true, fmt.Errorf("player: reset upgraded talent usage: %w", err)
+ }
+ }
// TalentSkillUpgradeResponse.item_info is an optional grant list. Current
// GameData defines no refund, so the correct protobuf response is empty.
s.talentApplied[ledgerKey] = reply
@@ -935,7 +945,7 @@ func (s *TalentUseService) healing(ctx command.Context, request []byte, operatio
var owned bool
character, owned = s.characters.Find(ctx, index)
meta, ok := s.design.Characters[character.ID]
- if !owned || !ok || meta.BannedPacks[pack] {
+ if !owned || !ok || character.HP == 0 || meta.BannedPacks[pack] {
return fail(fmt.Errorf("player: invalid healing caster"))
}
rule, ok = s.design.Rules[[2]uint64{meta.Group, character.TalentLevel}]
@@ -982,10 +992,8 @@ func (s *TalentUseService) healing(ctx command.Context, request []byte, operatio
return fail(fmt.Errorf("player: recovery cost overflow"))
}
if rule.Catalyst > 0 {
- if rule.Catalyst > 0 {
- if _, err = s.wallet.SpendCatalystOnce(ctx, identity, rule.Catalyst*uint64(len(ids))); err != nil {
- return fail(err)
- }
+ if _, err = s.wallet.SpendCatalystOnce(ctx, identity, rule.Catalyst*uint64(len(ids))); err != nil {
+ return fail(err)
}
}
}
diff --git a/go/internal/server/domain/roster/recruit.go b/go/internal/server/domain/roster/recruit.go
index 2cd44fd..e782a65 100644
--- a/go/internal/server/domain/roster/recruit.go
+++ b/go/internal/server/domain/roster/recruit.go
@@ -1,14 +1,13 @@
package roster
import (
+ "bd2server/internal/common/util"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
assets "bd2server/internal/server/domain/inventory"
- "crypto/rand"
"errors"
"fmt"
"math"
- "math/big"
"slices"
"strconv"
@@ -90,11 +89,10 @@ func (s *RecruitService) rollSpecial(count uint64) (specialRecruitState, error)
}
total += s.design.Rules[id].AppearProb
}
- draw, e := rand.Int(rand.Reader, new(big.Int).SetUint64(total))
+ n, e := util.RandomUint64N(total)
if e != nil {
return state, e
}
- n := draw.Uint64()
for i, id := range pool {
w := s.design.Rules[id].AppearProb
if n < w {
diff --git a/go/internal/server/domain/roster/spine_interaction.go b/go/internal/server/domain/roster/spine_interaction.go
new file mode 100644
index 0000000..12b4f6f
--- /dev/null
+++ b/go/internal/server/domain/roster/spine_interaction.go
@@ -0,0 +1,257 @@
+package roster
+
+import (
+ "encoding/binary"
+ "encoding/json"
+ "fmt"
+ "slices"
+ "strconv"
+ "strings"
+
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+type InteractionService struct {
+ Store stateio.Store
+ Design *gamedata.SpineInteractionDesign
+ Authorize func(command.Context, uint64) (bool, error)
+ Grant func(command.Context, string, []gamedata.Reward) ([]byte, error)
+}
+
+type interactionProgress struct {
+ Points map[string][]uint64 `json:"points"`
+ Claims map[string]bool `json:"claims"`
+}
+
+func interactionKey(k gamedata.InteractionPointKey) string {
+ return fmt.Sprintf("%d:%d:%d", k[0], k[1], k[2])
+}
+
+func interactionIdentity(raw []byte) (gamedata.InteractionPointKey, error) {
+ var key gamedata.InteractionPointKey
+ for i := range key {
+ n, found, err := wire.Varint(raw, i+1)
+ if err != nil || !found || n == 0 || n > 1<<31-1 {
+ return key, fmt.Errorf("interaction: invalid point identity")
+ }
+ key[i] = n
+ }
+ return key, nil
+}
+
+func (s InteractionService) Handle(ctx command.Context, path string, request []byte) (int, []byte, bool, error) {
+ codes := map[string]int{"/SpineInteractionAchievementInfo": 532, "/SpineInteractionAchievementSave": 533, "/SpineInteractionRewardInfo": 548, "/SpineInteractionReward": 549}
+ code, ok := codes[path]
+ if !ok {
+ return 0, nil, false, nil
+ }
+ fail := func(err error) (int, []byte, bool, error) { return code, nil, true, err }
+ if seq, found, err := wire.Varint(request, 1); err != nil || !found || seq == 0 {
+ return fail(fmt.Errorf("interaction: invalid request sequence"))
+ }
+ if s.Store == nil || s.Design == nil || s.Authorize == nil || s.Grant == nil {
+ return fail(fmt.Errorf("interaction: missing dependencies"))
+ }
+ st := interactionProgress{Points: map[string][]uint64{}, Claims: map[string]bool{}}
+ raw, err := s.Store.Load(ctx.State, "spine_interaction")
+ if err != nil {
+ return fail(err)
+ }
+ if raw != nil {
+ if err := stateio.RequireExactJSONObject(raw, "points", "claims"); err != nil {
+ return fail(err)
+ }
+ if err := json.Unmarshal(raw, &st); err != nil || st.Points == nil || st.Claims == nil {
+ return fail(fmt.Errorf("interaction: invalid saved progress"))
+ }
+ }
+ var out []byte
+ switch path {
+ case "/SpineInteractionAchievementInfo":
+ out, err = interactionInfo(st.Points)
+ case "/SpineInteractionRewardInfo":
+ keys := make([]string, 0, len(st.Claims))
+ for key := range st.Claims {
+ keys = append(keys, key)
+ }
+ slices.Sort(keys)
+ for _, key := range keys {
+ k, parseErr := parseInteractionKey(key)
+ if parseErr != nil {
+ return fail(parseErr)
+ }
+ out = wire.AppendBytes(out, 1, interactionPointWire(k))
+ }
+ case "/SpineInteractionAchievementSave":
+ err = s.savePoints(ctx, request, st.Points)
+ case "/SpineInteractionReward":
+ row, found, parseErr := wire.Bytes(request, 2)
+ if parseErr != nil || !found {
+ return fail(fmt.Errorf("interaction: missing reward point"))
+ }
+ key, parseErr := interactionIdentity(row)
+ if parseErr != nil {
+ return fail(parseErr)
+ }
+ point, known := s.Design.Points[key]
+ if !known || len(s.Design.Rewards[point.RewardGroup]) == 0 {
+ return fail(fmt.Errorf("interaction: point has no reward"))
+ }
+ if allowed, accessErr := s.Authorize(ctx, key[0]); accessErr != nil || !allowed {
+ return fail(fmt.Errorf("interaction: group unavailable: %v", accessErr))
+ }
+ if st.Claims[interactionKey(key)] {
+ return code, wire.AppendBytes(nil, 1, nil), true, nil
+ }
+ bundle, grantErr := s.Grant(ctx, "interaction:"+interactionKey(key), s.Design.Rewards[point.RewardGroup])
+ if grantErr != nil {
+ return fail(grantErr)
+ }
+ st.Claims[interactionKey(key)] = true
+ out = wire.AppendBytes(nil, 1, bundle)
+ }
+ if err != nil {
+ return fail(err)
+ }
+ if path == "/SpineInteractionAchievementSave" || path == "/SpineInteractionReward" {
+ raw, err = json.Marshal(st)
+ if err == nil {
+ err = s.Store.Save(ctx.State, "spine_interaction", raw)
+ }
+ if err != nil {
+ return fail(err)
+ }
+ }
+ return code, out, true, nil
+}
+
+func (s InteractionService) savePoints(ctx command.Context, request []byte, points map[string][]uint64) error {
+ if len(request) > 256<<10 {
+ return fmt.Errorf("interaction: save too large")
+ }
+ authorized := map[uint64]bool{}
+ return wire.Walk(request, func(row wire.Field) error {
+ if row.Number != 2 {
+ return nil
+ }
+ if row.Type != 2 {
+ return fmt.Errorf("interaction: invalid achievement row")
+ }
+ group, _, err := wire.Varint(row.Value, 1)
+ if err != nil || group == 0 || group > 1<<31-1 {
+ return fmt.Errorf("interaction: invalid group")
+ }
+ section, _, err := wire.Varint(row.Value, 2)
+ if err != nil || section == 0 || section > 1<<31-1 {
+ return fmt.Errorf("interaction: invalid section")
+ }
+ if !authorized[group] {
+ allowed, err := s.Authorize(ctx, group)
+ if err != nil || !allowed {
+ return fmt.Errorf("interaction: group unavailable: %v", err)
+ }
+ authorized[group] = true
+ }
+ return wire.Walk(row.Value, func(f wire.Field) error {
+ if f.Number != 3 {
+ return nil
+ }
+ if f.Type != 2 {
+ return fmt.Errorf("interaction: invalid point")
+ }
+ id, _, err := wire.Varint(f.Value, 1)
+ key := gamedata.InteractionPointKey{group, section, id}
+ point, known := s.Design.Points[key]
+ if err != nil || !known || !point.Achievement {
+ return fmt.Errorf("interaction: point not an achievement")
+ }
+ motions := append([]uint64{}, points[interactionKey(key)]...)
+ err = wire.Walk(f.Value, func(m wire.Field) error {
+ if m.Number != 2 {
+ return nil
+ }
+ if m.Type != 0 && m.Type != 2 {
+ return fmt.Errorf("interaction: invalid motion encoding")
+ }
+ for remaining := m.Value; len(remaining) > 0; {
+ n, count := binary.Uvarint(remaining)
+ if count <= 0 || !point.Motions[n] {
+ return fmt.Errorf("interaction: motion does not belong to point")
+ }
+ if !slices.Contains(motions, n) {
+ motions = append(motions, n)
+ }
+ remaining = remaining[count:]
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+ if len(point.Motions) != 0 && len(motions) == 0 {
+ return fmt.Errorf("interaction: required motions missing")
+ }
+ slices.Sort(motions)
+ points[interactionKey(key)] = motions
+ return nil
+ })
+ })
+}
+
+func parseInteractionKey(text string) (gamedata.InteractionPointKey, error) {
+ var key gamedata.InteractionPointKey
+ parts := strings.Split(text, ":")
+ if len(parts) != len(key) {
+ return key, fmt.Errorf("interaction: malformed saved point")
+ }
+ for i, part := range parts {
+ n, err := strconv.ParseUint(part, 10, 31)
+ if err != nil || n == 0 {
+ return key, fmt.Errorf("interaction: malformed saved point")
+ }
+ key[i] = n
+ }
+ return key, nil
+}
+
+func interactionPointWire(key gamedata.InteractionPointKey) []byte {
+ row := wire.AppendVarint(nil, 1, key[0])
+ row = wire.AppendVarint(row, 2, key[1])
+ return wire.AppendVarint(row, 3, key[2])
+}
+
+func interactionInfo(points map[string][]uint64) ([]byte, error) {
+ keys := make([]gamedata.InteractionPointKey, 0, len(points))
+ for text := range points {
+ key, err := parseInteractionKey(text)
+ if err != nil {
+ return nil, err
+ }
+ keys = append(keys, key)
+ }
+ slices.SortFunc(keys, func(a, b gamedata.InteractionPointKey) int { return slices.Compare(a[:], b[:]) })
+ var out, group []byte
+ var previous gamedata.InteractionPointKey
+ for _, key := range keys {
+ if key[0] != previous[0] || key[1] != previous[1] {
+ if group != nil {
+ out = wire.AppendBytes(out, 1, group)
+ }
+ group = wire.AppendVarint(nil, 1, key[0])
+ group = wire.AppendVarint(group, 2, key[1])
+ }
+ row := wire.AppendVarint(nil, 1, key[2])
+ for _, motion := range points[interactionKey(key)] {
+ row = wire.AppendVarint(row, 2, motion)
+ }
+ group = wire.AppendBytes(group, 3, row)
+ previous = key
+ }
+ if group != nil {
+ out = wire.AppendBytes(out, 1, group)
+ }
+ return out, nil
+}
diff --git a/go/internal/server/domain/roster/spine_recordings.go b/go/internal/server/domain/roster/spine_recordings.go
new file mode 100644
index 0000000..b358e1e
--- /dev/null
+++ b/go/internal/server/domain/roster/spine_recordings.go
@@ -0,0 +1,450 @@
+package roster
+
+import (
+ "bytes"
+ "compress/gzip"
+ "crypto/sha256"
+ "crypto/subtle"
+ "encoding/base64"
+ "encoding/binary"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "hash/crc32"
+ "io"
+ "math"
+ "slices"
+ "strconv"
+ "strings"
+ "unicode/utf8"
+
+ "bd2server/internal/common/util"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+var ErrRecordNotFound = errors.New("interaction recording not found")
+
+const recordDomain = "collection"
+const recordMetadataBucket = "spine_record_metadata"
+const recordDataBucket = "spine_record_data"
+
+type InteractionRecordService struct {
+ Store stateio.ScopedEntryStore
+ Design *gamedata.SpineInteractionDesign
+ Authorize func(command.Context, uint64) (bool, error)
+ RecordDataURL func(command.Context, uint64, string) (string, error)
+ CheckText func(command.Context, string, string) error
+}
+
+type interactionRecording struct {
+ Index uint64 `json:"index"`
+ Group uint64 `json:"group"`
+ Name string `json:"name"`
+ Capability string `json:"capability"`
+ Digest string `json:"digest"`
+}
+
+func (s InteractionRecordService) authorize(ctx command.Context, group uint64) error {
+ if s.Design == nil || s.Authorize == nil || !s.Design.RecordGroups[group] {
+ return ErrRecordNotFound
+ }
+ allowed, err := s.Authorize(ctx, group)
+ if err != nil {
+ return err
+ }
+ if !allowed {
+ return ErrRecordNotFound
+ }
+ return nil
+}
+
+func (s InteractionRecordService) metadata(ctx command.Context, index uint64) (interactionRecording, error) {
+ var row interactionRecording
+ if s.Store == nil || ctx.State == nil || index == 0 || index > math.MaxInt32 {
+ return row, ErrRecordNotFound
+ }
+ raw, found, err := s.Store.LoadEntry(ctx.State, recordDomain, recordMetadataBucket, strconv.FormatUint(index, 10))
+ if err != nil {
+ return row, err
+ }
+ if !found {
+ return row, ErrRecordNotFound
+ }
+ return decodeInteractionRecording(raw, index)
+}
+
+func decodeInteractionRecording(raw []byte, index uint64) (interactionRecording, error) {
+ var row interactionRecording
+ if err := stateio.RequireExactJSONObject(raw, "index", "group", "name", "capability", "digest"); err != nil {
+ return row, err
+ }
+ if err := json.Unmarshal(raw, &row); err != nil {
+ return row, err
+ }
+ capability, capErr := base64.RawURLEncoding.DecodeString(row.Capability)
+ digest, digestErr := hex.DecodeString(row.Digest)
+ if row.Index != index || row.Group == 0 || row.Name == "" || capErr != nil || len(capability) != 32 || digestErr != nil || len(digest) != sha256.Size {
+ return row, fmt.Errorf("interaction recording: corrupt metadata")
+ }
+ return row, nil
+}
+
+// LoadRecordData authenticates a download capability inside the account's command scope.
+func (s InteractionRecordService) LoadRecordData(ctx command.Context, index uint64, capability string) ([]byte, error) {
+ row, err := s.metadata(ctx, index)
+ if err != nil {
+ return nil, err
+ }
+ if subtle.ConstantTimeCompare([]byte(row.Capability), []byte(capability)) != 1 {
+ return nil, ErrRecordNotFound
+ }
+ if err = s.authorize(ctx, row.Group); err != nil {
+ return nil, err
+ }
+ return s.recordData(ctx, row)
+}
+
+func (s InteractionRecordService) recordData(ctx command.Context, row interactionRecording) ([]byte, error) {
+ raw, found, err := s.Store.LoadEntry(ctx.State, recordDomain, recordDataBucket, strconv.FormatUint(row.Index, 10))
+ if err != nil {
+ return nil, err
+ }
+ if !found {
+ return nil, ErrRecordNotFound
+ }
+ digest := sha256.Sum256(raw)
+ if hex.EncodeToString(digest[:]) != row.Digest {
+ return nil, fmt.Errorf("interaction recording: corrupt payload")
+ }
+ return raw, nil
+}
+
+func (s InteractionRecordService) url(ctx command.Context, row interactionRecording) (string, error) {
+ if s.RecordDataURL == nil {
+ return "", fmt.Errorf("interaction recording: missing download URL provider")
+ }
+ url, err := s.RecordDataURL(ctx, row.Index, row.Capability)
+ if err == nil && url == "" {
+ err = fmt.Errorf("interaction recording: empty download URL")
+ }
+ return url, err
+}
+
+func (s InteractionRecordService) Handle(ctx command.Context, path string, request []byte) (int, []byte, bool, error) {
+ codes := map[string]int{"/SpineInteractionRecordInfo": 571, "/SpineInteractionRecordDetailInfo": 572, "/SpineInteractionRecordSave": 573, "/SpineInteractionRecordDelete": 574, "/SpineInteractionRecordDataUpdate": 575, "/SpineInteractionRecordNameUpdate": 576}
+ code, found := codes[path]
+ if !found {
+ return 0, nil, false, nil
+ }
+ fail := func(err error) (int, []byte, bool, error) { return code, nil, true, err }
+ if s.Store == nil || s.Design == nil || s.Authorize == nil || ctx.State == nil {
+ return fail(fmt.Errorf("interaction recording: missing dependencies"))
+ }
+ seq, found, err := wire.Varint(request, 1)
+ if err != nil || !found || seq == 0 || seq > math.MaxInt32 || len(request) > (4<<20)+1024 {
+ return fail(fmt.Errorf("interaction recording: invalid request"))
+ }
+ if path == "/SpineInteractionRecordInfo" {
+ entries, err := s.Store.ListEntries(ctx.State, recordDomain, recordMetadataBucket)
+ if err != nil {
+ return fail(err)
+ }
+ indices := make([]uint64, 0, len(entries))
+ for key := range entries {
+ n, err := strconv.ParseUint(key, 10, 31)
+ if err != nil || n == 0 {
+ return fail(fmt.Errorf("interaction recording: corrupt index"))
+ }
+ indices = append(indices, n)
+ }
+ slices.Sort(indices)
+ var out []byte
+ authorized := map[uint64]bool{}
+ for _, index := range indices {
+ row, err := decodeInteractionRecording(entries[strconv.FormatUint(index, 10)], index)
+ if err != nil {
+ return fail(err)
+ }
+ if allowed, checked := authorized[row.Group]; checked {
+ if !allowed {
+ continue
+ }
+ } else {
+ err = s.authorize(ctx, row.Group)
+ if errors.Is(err, ErrRecordNotFound) {
+ authorized[row.Group] = false
+ continue
+ } else if err != nil {
+ return fail(err)
+ }
+ authorized[row.Group] = true
+ }
+ url, err := s.url(ctx, row)
+ if err != nil {
+ return fail(err)
+ }
+ p := wire.AppendVarint(nil, 1, row.Index)
+ p = wire.AppendVarint(p, 2, row.Group)
+ p = wire.AppendBytes(p, 3, []byte(row.Name))
+ p = wire.AppendBytes(p, 4, []byte(url))
+ out = wire.AppendBytes(out, 1, p)
+ }
+ return code, out, true, nil
+ }
+ index, _, err := wire.Varint(request, 2)
+ if err != nil || index == 0 || index > math.MaxInt32 {
+ return fail(ErrRecordNotFound)
+ }
+ var row interactionRecording
+ var counter []byte
+ if path == "/SpineInteractionRecordSave" {
+ if err = s.authorize(ctx, index); err != nil {
+ return fail(err)
+ }
+ entries, err := s.Store.ListEntries(ctx.State, recordDomain, recordMetadataBucket)
+ if err != nil {
+ return fail(err)
+ }
+ count := uint64(0)
+ for key, payload := range entries {
+ n, err := strconv.ParseUint(key, 10, 31)
+ if err != nil {
+ return fail(err)
+ }
+ r, err := decodeInteractionRecording(payload, n)
+ if err != nil {
+ return fail(err)
+ }
+ if r.Group == index {
+ count++
+ }
+ }
+ if count >= s.Design.RecordSaveSlots {
+ return fail(fmt.Errorf("interaction recording: save slots full"))
+ }
+ raw, exists, err := s.Store.LoadEntry(ctx.State, recordDomain, "spine_record_counter", "next")
+ if err != nil {
+ return fail(err)
+ }
+ next := uint64(1)
+ if exists {
+ next, err = strconv.ParseUint(string(raw), 10, 31)
+ if err != nil || next == 0 {
+ return fail(fmt.Errorf("interaction recording: corrupt counter"))
+ }
+ }
+ if next >= math.MaxInt32 {
+ return fail(fmt.Errorf("interaction recording: index exhausted"))
+ }
+ if _, exists := entries[strconv.FormatUint(next, 10)]; exists {
+ return fail(fmt.Errorf("interaction recording: counter collision"))
+ }
+ row = interactionRecording{Index: next, Group: index, Name: fmt.Sprintf("Record %d", next)}
+ counter = []byte(strconv.FormatUint(next+1, 10))
+ } else {
+ row, err = s.metadata(ctx, index)
+ if err != nil {
+ return fail(err)
+ }
+ if err = s.authorize(ctx, row.Group); err != nil {
+ return fail(err)
+ }
+ }
+ key := strconv.FormatUint(row.Index, 10)
+ if path == "/SpineInteractionRecordDetailInfo" {
+ raw, err := s.recordData(ctx, row)
+ if err != nil {
+ return fail(err)
+ }
+ return code, wire.AppendBytes(nil, 1, raw), true, nil
+ }
+ if path == "/SpineInteractionRecordDelete" {
+ err := s.Store.SaveWithEntries(ctx.State, recordDomain, nil, []stateio.EntryMutation{{Bucket: recordMetadataBucket, Key: key, Delete: true}, {Bucket: recordDataBucket, Key: key, Delete: true}})
+ return code, nil, true, err
+ }
+ var changes []stateio.EntryMutation
+ var out []byte
+ if path == "/SpineInteractionRecordNameUpdate" {
+ name, _, err := wire.Bytes(request, 3)
+ if err != nil || !validRecordingName(string(name)) {
+ return fail(fmt.Errorf("interaction recording: invalid name"))
+ }
+ if s.CheckText == nil {
+ return fail(fmt.Errorf("interaction recording: missing text policy"))
+ }
+ if err = s.CheckText(ctx, "spine_record_name", string(name)); err != nil {
+ return fail(err)
+ }
+ row.Name = string(name)
+ } else {
+ data, _, err := wire.Bytes(request, 3)
+ if err != nil {
+ return fail(err)
+ }
+ if err = s.validateRecording(row.Group, data); err != nil {
+ return fail(err)
+ }
+ capability, err := util.RandomBase64URL(32)
+ if err != nil {
+ return fail(err)
+ }
+ row.Capability = capability
+ digest := sha256.Sum256(data)
+ row.Digest = hex.EncodeToString(digest[:])
+ url, err := s.url(ctx, row)
+ if err != nil {
+ return fail(err)
+ }
+ if path == "/SpineInteractionRecordSave" {
+ out = wire.AppendVarint(nil, 1, row.Index)
+ out = wire.AppendBytes(out, 2, []byte(row.Name))
+ out = wire.AppendBytes(out, 3, []byte(url))
+ changes = append(changes, stateio.EntryMutation{Bucket: "spine_record_counter", Key: "next", Payload: counter})
+ } else {
+ out = wire.AppendBytes(nil, 1, []byte(url))
+ }
+ changes = append(changes, stateio.EntryMutation{Bucket: recordDataBucket, Key: key, Payload: data})
+ }
+ raw, err := json.Marshal(row)
+ if err != nil {
+ return fail(err)
+ }
+ changes = append(changes, stateio.EntryMutation{Bucket: recordMetadataBucket, Key: key, Payload: raw})
+ if err = s.Store.SaveWithEntries(ctx.State, recordDomain, nil, changes); err != nil {
+ return fail(err)
+ }
+ return code, out, true, nil
+}
+
+func validRecordingName(name string) bool {
+ if !utf8.ValidString(name) || strings.Trim(name, " ") == "" {
+ return false
+ }
+ count := 0
+ for _, c := range name {
+ allowed := c == ' ' || c >= '0' && c <= '9' || c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= 0xac00 && c <= 0xd7a3 || c >= 0x3041 && c <= 0x30fe || c >= 0x4e00 && c <= 0x9fd5 || c >= 0x180 && c <= 0x24f
+ if !allowed {
+ return false
+ }
+ count++
+ if c >= 0xac00 && c <= 0xd7a3 || c >= 0x4e00 && c <= 0x9fff || c >= 0x3040 && c <= 0x30fc {
+ count++
+ }
+ }
+ return count >= 4 && count <= 20
+}
+
+type recordingReader struct{ *bytes.Reader }
+
+func (r recordingReader) integer() (int64, error) {
+ var n uint32
+ for shift := uint(0); shift < 35; shift += 7 {
+ b, err := r.ReadByte()
+ if err != nil {
+ return 0, err
+ }
+ if shift == 28 && b > 15 {
+ return 0, fmt.Errorf("interaction recording: integer overflow")
+ }
+ n |= uint32(b&127) << shift
+ if b&128 == 0 {
+ return int64(int32(n>>1) ^ -int32(n&1)), nil
+ }
+ }
+ return 0, fmt.Errorf("interaction recording: invalid integer")
+}
+
+func (s InteractionRecordService) validateRecording(group uint64, data []byte) error {
+ invalid := func() error { return fmt.Errorf("interaction recording: invalid native event data") }
+ if len(data) < 6 || len(data) > 4<<20 || data[4] != 1 || s.Design.MaxRecordTime == 0 || s.Design.MaxRecordInteractions == 0 {
+ return invalid()
+ }
+ compressed := bytes.NewReader(data[5:])
+ gz, err := gzip.NewReader(compressed)
+ if err != nil {
+ return invalid()
+ }
+ gz.Multistream(false)
+ raw, err := io.ReadAll(io.LimitReader(gz, (16<<20)+1))
+ closeErr := gz.Close()
+ if err != nil || closeErr != nil || len(raw) > 16<<20 || compressed.Len() != 0 || crc32.ChecksumIEEE(raw) != binary.LittleEndian.Uint32(data[:4]) || len(raw) < 4 {
+ return invalid()
+ }
+ count := uint64(binary.LittleEndian.Uint32(raw[:4]))
+ if count == 0 || count > 100000 {
+ return invalid()
+ }
+ r := recordingReader{bytes.NewReader(raw[4:])}
+ var timeMS, interactions, dragCount uint64
+ limitMS := s.Design.MaxRecordTime * 1000
+ for range count {
+ flags, err := r.ReadByte()
+ if err != nil || flags&^byte(31) != 0 || (flags&7 != 1 && flags&7 != 2 && flags&7 != 4) {
+ return invalid()
+ }
+ delta, e1 := r.integer()
+ section, e2 := r.integer()
+ point, e3 := r.integer()
+ tool, e4 := r.integer()
+ if e1 != nil || e2 != nil || e3 != nil || e4 != nil || delta < 0 || section <= 0 || point <= 0 || tool < 0 {
+ return invalid()
+ }
+ if _, known := s.Design.Points[gamedata.InteractionPointKey{group, uint64(section), uint64(point)}]; !known || !s.Design.RecordTools[uint64(tool)] {
+ return invalid()
+ }
+ timeMS += uint64(delta)
+ if timeMS > limitMS {
+ return invalid()
+ }
+ if flags&5 != 0 {
+ interactions++
+ if interactions > s.Design.MaxRecordInteractions {
+ return invalid()
+ }
+ }
+ if flags&4 != 0 {
+ n, err := r.integer()
+ if err != nil || n < 0 || n > 100000 {
+ return invalid()
+ }
+ dragCount += uint64(n)
+ if dragCount > 100000 {
+ return invalid()
+ }
+ dragTime := timeMS
+ for j := range n {
+ kind, e1 := r.ReadByte()
+ overlap, e2 := r.ReadByte()
+ dt, e3 := r.integer()
+ _, e4 := r.integer()
+ _, e5 := r.integer()
+ if e1 != nil || e2 != nil || e3 != nil || e4 != nil || e5 != nil || kind > 1 || overlap > 1 || dt < 0 || kind == 1 && j != n-1 {
+ return invalid()
+ }
+ dragTime += uint64(dt)
+ if dragTime > limitMS {
+ return invalid()
+ }
+ }
+ }
+ if flags&8 != 0 {
+ var scores [2]float32
+ if binary.Read(r, binary.LittleEndian, &scores) != nil {
+ return invalid()
+ }
+ for _, score := range scores {
+ if math.IsNaN(float64(score)) || math.IsInf(float64(score), 0) {
+ return invalid()
+ }
+ }
+ }
+ }
+ if r.Len() != 0 {
+ return invalid()
+ }
+ return nil
+}
diff --git a/go/internal/server/domain/roster/talent_dispatch.go b/go/internal/server/domain/roster/talent_dispatch.go
index e4147ef..20f34bd 100644
--- a/go/internal/server/domain/roster/talent_dispatch.go
+++ b/go/internal/server/domain/roster/talent_dispatch.go
@@ -1,13 +1,12 @@
package roster
import (
+ "bd2server/internal/common/util"
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/storage/stateio"
- "crypto/rand"
"encoding/json"
"fmt"
- "math/big"
"time"
)
@@ -51,11 +50,7 @@ func OpenTalentDispatch(store stateio.Store, d map[uint64]gamedata.TalentDispatc
if n == 0 {
return 0, fmt.Errorf("dispatch: empty pool")
}
- v, e := rand.Int(rand.Reader, new(big.Int).SetUint64(n))
- if e != nil {
- return 0, e
- }
- return v.Uint64(), nil
+ return util.RandomUint64N(n)
}}, nil
}
func (s *TalentDispatchService) load(ctx command.Context) (talentDispatchState, error) {
diff --git a/go/internal/server/domain/roster/talent_use.go b/go/internal/server/domain/roster/talent_use.go
index b0a5ae1..6506633 100644
--- a/go/internal/server/domain/roster/talent_use.go
+++ b/go/internal/server/domain/roster/talent_use.go
@@ -51,7 +51,9 @@ func NewTalentUseService(d *gamedata.TalentUseDesign, store stateio.Store, chara
if d == nil || store == nil || characters == nil || inventory == nil || wallet == nil || economy == nil {
return nil, fmt.Errorf("player: missing talent use dependencies")
}
- return &TalentUseService{design: d, store: store, characters: characters, inventory: inventory, wallet: wallet, economy: economy, effects: map[uint64]TalentUseEffect{}, now: time.Now}, nil
+ s := &TalentUseService{design: d, store: store, characters: characters, inventory: inventory, wallet: wallet, economy: economy, effects: map[uint64]TalentUseEffect{}, now: time.Now}
+ characters.talentUpgraded = s.resetUpgradedTalent
+ return s, nil
}
func (s *TalentUseService) AttachContext(ctx command.Context, f TalentUseContext) { s.context = f }
func (s *TalentUseService) AttachEffect(class uint64, f TalentUseEffect) { s.effects[class] = f }
@@ -76,7 +78,29 @@ func (s *TalentUseService) load(ctx command.Context) (talentUseSnapshot, error)
func sha256Sum(b []byte) []byte { v := sha256.Sum256(b); return v[:] }
func talentNPCClass(class uint64) bool { return class == 1 || class == 5 || class == 16 || class == 19 }
func talentHasCooldown(class uint64) bool {
- return class == 2 || class == 6 || class == 12 || class == 13 || class == 15 || class == 17
+ return class == 2 || class == 6 || class == 12 || class == 13 || class == 17
+}
+
+func (s *TalentUseService) resetUpgradedTalent(ctx command.Context, character Character) error {
+ meta := s.design.Characters[character.ID]
+ rule := s.design.Rules[[2]uint64{meta.Group, character.TalentLevel}]
+ if rule.Class != 3 {
+ return nil
+ }
+ v, err := s.load(ctx)
+ if err != nil {
+ return err
+ }
+ current := v.Skills[rule.Group]
+ current.Count = 0
+ current.Level = rule.Level
+ current.Settled = true
+ v.Skills[rule.Group] = current
+ raw, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+ return s.store.Save(ctx.State, "talentuse", raw)
}
func (s *TalentUseService) experienceMaximum(c Character) (uint64, error) {
@@ -119,6 +143,33 @@ func (s *TalentUseService) ShopDiscount(ctx command.Context, pack, npc uint64) (
return v.Discounts[ctx.SessionID+":"+fmt.Sprintf("%d/%d", pack, npc)], nil
}
+func (s *TalentUseService) ConsumeWaypoint(ctx command.Context, pack, mapID, seq uint64) error {
+ v, err := s.load(ctx)
+ if err != nil {
+ return err
+ }
+ key := "waypoint:pending:" + ctx.SessionID
+ digest := fmt.Sprintf("%d/%d", pack, mapID)
+ replayKey := fmt.Sprintf("waypoint:used:%s:%d", ctx.SessionID, seq)
+ if used, found := v.Receipts[replayKey]; found {
+ if used.Digest != digest {
+ return fmt.Errorf("player: changed waypoint talent replay")
+ }
+ return nil
+ }
+ permission, found := v.Receipts[key]
+ if !found || permission.Digest != digest {
+ return fmt.Errorf("player: waypoint travel has no matching talent cast pack=%d map=%d", pack, mapID)
+ }
+ delete(v.Receipts, key)
+ v.Receipts[replayKey] = talentUseReceipt{Digest: digest}
+ raw, err := json.Marshal(v)
+ if err != nil {
+ return err
+ }
+ return s.store.Save(ctx.State, "talentuse", raw)
+}
+
// ConsumeOverwhelm authorizes the follow-up result for one successful cast.
// The one-minute handoff window is this server's request policy, not a claimed
// official skill duration; the field domain validates every actual monster.
diff --git a/go/internal/server/domain/world/field_object_routes.go b/go/internal/server/domain/world/field_object_routes.go
index c73624a..97bd2b4 100644
--- a/go/internal/server/domain/world/field_object_routes.go
+++ b/go/internal/server/domain/world/field_object_routes.go
@@ -1,9 +1,6 @@
package world
-import (
- "bd2server/internal/server/domain/command"
- "fmt"
-)
+import "bd2server/internal/server/domain/command"
func (s *Service) fieldObjectCurrentPack(pack int) bool {
@@ -15,25 +12,6 @@ func (s *Service) fieldObjectCurrentPack(pack int) bool {
return current == pack
}
-func (s *Service) validateFieldObjectMap(ctx command.Context, pack, mapID int) error {
- _, saved := s.state.Position()
- _, event, err := s.resolveEventFieldPack(ctx, pack)
- if err != nil {
- return err
- }
- if !saved && !event {
- return nil
- }
- current, err := s.currentFieldMap(ctx, pack)
- if err != nil {
- return fmt.Errorf("%w: field object map unavailable (pack=%d object_map=%d): %v", ErrInvalidRequest, pack, mapID, err)
- }
- if current != mapID {
- return fmt.Errorf("%w: field object outside current map (pack=%d object_map=%d current_map=%d)", ErrInvalidRequest, pack, mapID, current)
- }
- return nil
-}
-
func (s *Service) rewardMonsterAvailable(ctx command.Context, pack, monster int) (bool, error) {
if s.fieldObjectLoader == nil && s.fieldObjects == nil {
return true, nil
diff --git a/go/internal/server/domain/world/field_reward_claim_integration_test.go b/go/internal/server/domain/world/field_reward_claim_integration_test.go
new file mode 100644
index 0000000..ed1ac49
--- /dev/null
+++ b/go/internal/server/domain/world/field_reward_claim_integration_test.go
@@ -0,0 +1,91 @@
+//go:build integration
+
+package world
+
+import (
+ "testing"
+
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/world/progress"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+// Native FieldPacket addresses rewards by pack/group/object, not current map.
+// GameData 20261012190548: pack9 green pot33011/group303 has buff19,
+// restoring 30% of maximum HP; its map92 metadata is also used by the HUD.
+func TestGreenPotClaimAfterMapChangeHealsOnlyOnce(t *testing.T) {
+ ctx, service, items, setMap := eventMonsterIntegration(t, 9)
+ versions, err := versionconfig.Find()
+ if err != nil {
+ t.Fatal(err)
+ }
+ source := gamedata.NewSource(versions.Resolve("data/resources/GameData"), versions.GameDataVersion)
+ if err := service.AttachFieldObjectRuntime(source, service.fieldReset); err != nil {
+ t.Fatal(err)
+ }
+ service.packs = map[int]map[int]gamedata.QuestDesign{9: service.storyCatalog.Packs[9].Quests}
+ maxHP, err := service.characters.MaxHealth(ctx, 1)
+ if err != nil || maxHP < 10 {
+ t.Fatalf("field character maximum HP: %d, %v", maxHP, err)
+ }
+ if err := service.characters.SetCurrentHealth(ctx, 1, 1); err != nil {
+ t.Fatal(err)
+ }
+ setMap(92)
+ setMap(93)
+ claim := func(group uint64) ([]byte, error) {
+ t.Helper()
+ request := wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(wire.AppendVarint(nil, 1, 1), 2, 9), 3, group), 4, 33011)
+ code, response, handled, err := service.Handle(ctx, "/FieldObjectReward", request)
+ if err == nil && (!handled || code != 29) {
+ t.Fatalf("native pot response unavailable: handled=%v code=%d", handled, code)
+ }
+ return response, err
+ }
+ if _, err := claim(302); err == nil {
+ t.Fatal("another object's group must not authorize this pot")
+ }
+ if hp, err := service.characters.CurrentHealth(ctx, 1); err != nil || hp != 1 {
+ t.Fatalf("rejected claim changed health: hp=%d err=%v", hp, err)
+ }
+ response, err := claim(303)
+ if err != nil {
+ t.Fatalf("native object claim after entering map93: %v", err)
+ }
+ if hp, err := service.characters.CurrentHealth(ctx, 1); err != nil || hp != 1+maxHP*3/10 {
+ t.Fatalf("green pot must restore 30%% maximum HP once: hp=%d max=%d err=%v", hp, maxHP, err)
+ }
+ var buffID uint64
+ if err := wire.Walk(response, func(f wire.Field) error {
+ if f.Number == 2 && f.Type == 2 {
+ var err error
+ buffID, _, err = wire.Varint(f.Value, 1)
+ return err
+ }
+ return nil
+ }); err != nil || buffID != 19 {
+ t.Fatalf("native client cannot apply pot effect: buff=%d err=%v", buffID, err)
+ }
+ if err := service.characters.SetCurrentHealth(ctx, 1, 1); err != nil {
+ t.Fatal(err)
+ }
+ service.state, err = progress.OpenStore(ctx, stateio.RootStore{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := claim(303); err != nil {
+ t.Fatalf("retry after state reload must acknowledge consumed pot: %v", err)
+ }
+ if hp, err := service.characters.CurrentHealth(ctx, 1); err != nil || hp != 1 {
+ t.Fatalf("retry healed from the same pot twice: hp=%d err=%v", hp, err)
+ }
+ if got := items.All(ctx); len(got) != 0 {
+ t.Fatal("healing pot granted inventory loot")
+ }
+ opened, err := service.openedFieldObjects(ctx, 9)
+ if err != nil || len(opened) != 1 || opened[0] != 33011 {
+ t.Fatalf("reloaded preview must retain consumed pot: opened=%v err=%v", opened, err)
+ }
+}
diff --git a/go/internal/server/domain/world/map_exploration.go b/go/internal/server/domain/world/map_exploration.go
new file mode 100644
index 0000000..363f4a6
--- /dev/null
+++ b/go/internal/server/domain/world/map_exploration.go
@@ -0,0 +1,94 @@
+package world
+
+import (
+ "fmt"
+ "slices"
+ "sort"
+ "strconv"
+
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/world/progress"
+ "bd2server/internal/server/protocol/wire"
+)
+
+func (s *Service) handleActiveMap(ctx command.Context, request []byte) (int, []byte, bool, error) {
+ fail := func(reason string) (int, []byte, bool, error) {
+ return 0, nil, true, fmt.Errorf("%w: map exploration %s", ErrInvalidRequest, reason)
+ }
+ pack, err := requestPack(request)
+ if err != nil {
+ return 0, nil, true, err
+ }
+ if !s.packUnlocked(ctx, pack) {
+ return fail("pack unavailable")
+ }
+ mapID, found, err := wire.Varint(request, 3)
+ if err != nil || !found || mapID == 0 || mapID > 1<<31-1 {
+ return fail("invalid map")
+ }
+ validMap := false
+ if event, found, err := s.resolveEventFieldPack(ctx, pack); err != nil {
+ return 0, nil, true, err
+ } else if found {
+ validMap = slices.Contains(event.MapIDs, int(mapID))
+ } else if field, found := s.fieldPacks[pack]; found {
+ validMap = field.MapIDs[int(mapID)]
+ } else {
+ design, err := s.packDetailDesign(pack)
+ if err != nil {
+ return 0, nil, true, err
+ }
+ validMap = slices.Contains(design.MapIDs, int(mapID))
+ }
+ if !validMap {
+ return fail("map outside pack")
+ }
+ var rows []byte
+ if err := wire.Walk(request, func(field wire.Field) error {
+ if field.Number != 4 {
+ return nil
+ }
+ if field.Type != 2 || len(rows) >= progress.MapExplorationRows || len(field.Value) > 2 {
+ return ErrInvalidRequest
+ }
+ value := uint64(0)
+ if len(field.Value) != 0 {
+ var err error
+ value, err = strconv.ParseUint(string(field.Value), 16, 8)
+ if err != nil {
+ return ErrInvalidRequest
+ }
+ }
+ rows = append(rows, byte(value))
+ return nil
+ }); err != nil || len(rows) != progress.MapExplorationRows {
+ return fail("invalid row masks")
+ }
+ err = s.state.RevealMap(ctx, pack, int(mapID), rows)
+ return 0, nil, true, err
+}
+
+func (s *Service) mapExplorationWire(ctx command.Context, pack int) ([]byte, error) {
+ maps, err := s.state.MapExploration(ctx, pack)
+ if err != nil {
+ return nil, err
+ }
+ ids := make([]int, 0, len(maps))
+ for id := range maps {
+ ids = append(ids, id)
+ }
+ sort.Ints(ids)
+ var out []byte
+ for _, id := range ids {
+ row := wire.AppendVarint(nil, 1, uint64(id))
+ for _, mask := range maps[id] {
+ text := ""
+ if mask != 0 {
+ text = strconv.FormatUint(uint64(mask), 16)
+ }
+ row = wire.AppendString(row, 2, text)
+ }
+ out = wire.AppendBytes(out, 10, row)
+ }
+ return out, nil
+}
diff --git a/go/internal/server/domain/world/npc_reputation.go b/go/internal/server/domain/world/npc_reputation.go
index c55d844..92a9eae 100644
--- a/go/internal/server/domain/world/npc_reputation.go
+++ b/go/internal/server/domain/world/npc_reputation.go
@@ -3,9 +3,11 @@ package world
import (
"bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
"bd2server/internal/server/storage/stateio"
"encoding/json"
"fmt"
+ "slices"
"time"
)
@@ -59,15 +61,54 @@ func (s *Service) reputationState(ctx command.Context, pack int, rule gamedata.N
if err != nil {
return 0, 0, err
}
+ state, elapsed := s.npcReputation.state(v, pack, rule)
+ return state, elapsed, nil
+}
+
+func (r *npcReputationRuntime) state(v npcReputationSnapshot, pack int, rule gamedata.NPCReputationRule) (uint64, uint64) {
start, ok := v.Starts[reputationKey(pack, rule.ID)]
if !ok {
- return 1, 0, nil
+ return 1, 0
}
- elapsed := max(s.npcReputation.now().Unix()-start, 0)
+ elapsed := max(r.now().Unix()-start, 0)
if uint64(elapsed) >= rule.DownHours*3600 {
- return 1, 0, nil
+ return 1, 0
}
- return 2, uint64(elapsed), nil
+ return 2, uint64(elapsed)
+}
+
+func (s *Service) reputationInfo(ctx command.Context, request []byte) (int, []byte, bool, error) {
+ seq, found, err := wire.Varint(request, 1)
+ if err != nil || !found || seq == 0 || s.npcReputation == nil {
+ return 106, nil, true, ErrInvalidRequest
+ }
+ v, err := s.npcReputation.snapshot(ctx)
+ if err != nil {
+ return 106, nil, true, err
+ }
+ current, err := s.CurrentPackID(ctx)
+ if err != nil {
+ return 106, nil, true, err
+ }
+ d, err := s.npcReputation.load(current)
+ if err != nil {
+ return 106, nil, true, err
+ }
+ rows := make(map[uint64][]byte, len(d.Groups))
+ for id, rule := range d.Groups {
+ state, elapsed := s.npcReputation.state(v, current, rule)
+ rows[id] = reputationWire(id, state, elapsed)
+ }
+ ids := make([]uint64, 0, len(rows))
+ for id := range rows {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ var out []byte
+ for _, id := range ids {
+ out = wire.AppendBytes(out, 1, rows[id])
+ }
+ return 106, out, true, nil
}
func (s *Service) NPCShopReputation(ctx command.Context, pack uint64) (uint64, uint64, error) {
diff --git a/go/internal/server/domain/world/npc_reputation_download_integration_test.go b/go/internal/server/domain/world/npc_reputation_download_integration_test.go
new file mode 100644
index 0000000..b4e49ce
--- /dev/null
+++ b/go/internal/server/domain/world/npc_reputation_download_integration_test.go
@@ -0,0 +1,107 @@
+//go:build integration
+
+package world
+
+import (
+ "testing"
+ "time"
+
+ "bd2server/internal/common/versionconfig"
+ "bd2server/internal/server/design/gamedata"
+ "bd2server/internal/server/domain/command"
+ assets "bd2server/internal/server/domain/inventory"
+ "bd2server/internal/server/domain/world/progress"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/storage/stateio"
+)
+
+func TestReputationRefreshRestoresEarnedDiscountAndExpiresWithoutRenewingIt(t *testing.T) {
+ v, err := versionconfig.Find()
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := gamedata.CloseDatabaseCache(); err != nil {
+ t.Error(err)
+ }
+ })
+ source := gamedata.NewSource(v.Resolve("data/resources/GameData"), v.GameDataVersion)
+ catalog, err := gamedata.LoadStoryCatalog(source.Root(), source.Version())
+ if err != nil {
+ t.Fatal(err)
+ }
+ design, err := source.NPCReputation(1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var rule gamedata.NPCReputationRule
+ for _, candidate := range design.Groups {
+ if candidate.DownHours > 0 {
+ rule = candidate
+ break
+ }
+ }
+ if rule.ID == 0 {
+ t.Fatal("chapter has no expiring reputation")
+ }
+ now := time.Unix(1800000000, 0)
+ ctx := command.Context{Identity: command.Identity{AccountID: "reputation-player", SessionID: "session"}, State: stateio.NewMemory()}
+ open := func() *Service {
+ s := &Service{seed: Seed{PackID: 1}, activePack: 1, state: progress.NewStore(), storyCatalog: catalog}
+ s.squadLevel = func() (uint64, error) { return 1000, nil }
+ var err error
+ s.inventory, err = assets.OpenInventory(ctx, stateio.RootStore{}, []assets.Item{{InvenIndex: 98, Type: 19, ID: catalog.Packs[2].Open.TicketID, Count: 1}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := s.ConfigureNPCRuntime(source, stateio.RootStore{}); err != nil {
+ t.Fatal(err)
+ }
+ s.npcReputation.now = func() time.Time { return now }
+ return s
+ }
+ read := func(s *Service, wantState, wantElapsed uint64) {
+ t.Helper()
+ _, body, handled, err := s.Handle(ctx, "/ReputationInfo", wire.AppendVarint(nil, 1, 1))
+ if err != nil || !handled {
+ t.Fatalf("refresh: %v", err)
+ }
+ rows, err := nestedMessages(body, 1)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, row := range rows {
+ id, _, _ := wire.Varint(row, 1)
+ if id != rule.ID {
+ continue
+ }
+ state, _, _ := wire.Varint(row, 2)
+ elapsed, _, _ := wire.Varint(row, 3)
+ if state != wantState || elapsed != wantElapsed {
+ t.Fatalf("discount state=%d elapsed=%d", state, elapsed)
+ }
+ return
+ }
+ t.Fatal("refresh omitted the reputation group used by the field/shop")
+ }
+ s := open()
+ read(s, 1, 0)
+ if _, err := s.CompleteNPCReputation(ctx, "completed-commission", 1, rule.ID); err != nil {
+ t.Fatal(err)
+ }
+ now = now.Add(10 * time.Second)
+ s = open()
+ read(s, 2, 10)
+ s.activePack = 2
+ read(s, 1, 0)
+ s.activePack = 1
+ read(s, 2, 10)
+ if _, err := s.CompleteNPCReputation(ctx, "completed-commission", 1, rule.ID); err != nil {
+ t.Fatal(err)
+ }
+ read(open(), 2, 10)
+ now = now.Add(time.Duration(rule.DownHours) * time.Hour)
+ read(open(), 1, 0)
+ ctx.State = stateio.NewMemory()
+ read(open(), 1, 0)
+}
diff --git a/go/internal/server/domain/world/pack_purchase.go b/go/internal/server/domain/world/pack_purchase.go
index 42fb87b..5a94ae5 100644
--- a/go/internal/server/domain/world/pack_purchase.go
+++ b/go/internal/server/domain/world/pack_purchase.go
@@ -8,6 +8,7 @@ import (
)
func packPurchaseIdentity(id int) string { return fmt.Sprintf("pack-purchase:%d", id) }
+func packEntryIdentity(id int) string { return fmt.Sprintf("pack-entered:%d", id) }
func (s *Service) grantPurchaseRewards(ctx command.Context, identity string, rewards []gamedata.Reward) ([]assets.Item, error) {
var itemRewards []gamedata.BattleReward
diff --git a/go/internal/server/domain/world/progress/map_exploration.go b/go/internal/server/domain/world/progress/map_exploration.go
new file mode 100644
index 0000000..149ae36
--- /dev/null
+++ b/go/internal/server/domain/world/progress/map_exploration.go
@@ -0,0 +1,59 @@
+package progress
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "strconv"
+
+ "bd2server/internal/server/domain/command"
+)
+
+const MapExplorationRows = 8
+
+func (s *Store) MapExploration(ctx command.Context, pack int) (map[int][]byte, error) {
+ if ctx.State == nil || pack <= 0 {
+ return nil, fmt.Errorf("progress: map exploration requires account storage and pack")
+ }
+ raw, found, err := ctx.State.LoadEntry("progress", "map_exploration", strconv.Itoa(pack))
+ if err != nil {
+ return nil, err
+ }
+ maps := map[int][]byte{}
+ if !found {
+ return maps, nil
+ }
+ if err := json.Unmarshal(raw, &maps); err != nil || maps == nil {
+ return nil, fmt.Errorf("progress: invalid saved map exploration")
+ }
+ for id, rows := range maps {
+ if id <= 0 || len(rows) != MapExplorationRows {
+ return nil, fmt.Errorf("progress: invalid saved map exploration rows")
+ }
+ }
+ return maps, nil
+}
+
+func (s *Store) RevealMap(ctx command.Context, pack, id int, rows []byte) error {
+ if id <= 0 || len(rows) != MapExplorationRows {
+ return fmt.Errorf("progress: invalid map exploration rows")
+ }
+ maps, err := s.MapExploration(ctx, pack)
+ if err != nil {
+ return err
+ }
+ merged := make([]byte, MapExplorationRows)
+ copy(merged, maps[id])
+ for i, row := range rows {
+ merged[i] |= row
+ }
+ if bytes.Equal(merged, maps[id]) || bytes.Equal(merged, make([]byte, MapExplorationRows)) {
+ return nil
+ }
+ maps[id] = merged
+ raw, err := json.Marshal(maps)
+ if err != nil {
+ return err
+ }
+ return ctx.State.PutEntry("progress", "map_exploration", strconv.Itoa(pack), raw)
+}
diff --git a/go/internal/server/domain/world/protocol_field_adapter.go b/go/internal/server/domain/world/protocol_field_adapter.go
index f314d33..a651aec 100644
--- a/go/internal/server/domain/world/protocol_field_adapter.go
+++ b/go/internal/server/domain/world/protocol_field_adapter.go
@@ -613,9 +613,6 @@ func (s *Service) openFieldObjectResponse(ctx command.Context, pack, group, id i
if !ok || obj.GroupID != group || !s.packUnlocked(ctx, pack) || !s.fieldObjectCurrentPack(pack) {
return nil, ErrInvalidRequest
}
- if err := s.validateFieldObjectMap(ctx, pack, obj.MapID); err != nil {
- return nil, err
- }
period, err := s.fieldObjectPeriodFor(pack, obj)
if err != nil {
return nil, err
@@ -873,9 +870,6 @@ func (s *Service) openFieldObject(ctx command.Context, pack, group, id int) ([]b
if !exists || obj.GroupID != group || !s.packUnlocked(ctx, pack) || !s.fieldObjectCurrentPack(pack) {
return nil, fmt.Errorf("%w: unavailable field object", ErrInvalidRequest)
}
- if err := s.validateFieldObjectMap(ctx, pack, obj.MapID); err != nil {
- return nil, err
- }
period, err := s.fieldObjectPeriodFor(pack, obj)
if err != nil {
return nil, err
diff --git a/go/internal/server/domain/world/protocol_story_adapter.go b/go/internal/server/domain/world/protocol_story_adapter.go
index 5a2d974..b762570 100644
--- a/go/internal/server/domain/world/protocol_story_adapter.go
+++ b/go/internal/server/domain/world/protocol_story_adapter.go
@@ -81,7 +81,10 @@ func (s *Service) packInfoFor(ctx command.Context, packID int) ([]byte, error) {
}
func (s *Service) basePackInfoFor(ctx command.Context, packID int) ([]byte, error) {
- var out []byte
+ out, err := s.mapExplorationWire(ctx, packID)
+ if err != nil {
+ return nil, err
+ }
if active := s.firstUnclearedQuestFor(packID); active != 0 {
quest := s.questInfoWire(packID, active)
chars, _, err := s.resolveActivePartyWires(ctx, packID, active)
@@ -364,6 +367,10 @@ func (s *Service) resolveActivePartyWires(ctx command.Context, packID, questID i
}
func (s *Service) storyPackDBInfoRows(ctx command.Context) [][]byte {
+ played := make(map[int]bool)
+ for _, quest := range s.state.AllClearedQuests() {
+ played[quest.PackID] = true
+ }
ids := make([]int, 0, len(s.storyCatalog.Packs))
for id := range s.storyCatalog.Packs {
if s.storyCatalog.Packs[id].Type == 5 {
@@ -405,6 +412,10 @@ func (s *Service) storyPackDBInfoRows(ctx command.Context) [][]byte {
if s.collection != nil {
_, owned := s.collection.Grant(packPurchaseIdentity(id))
purchased = purchased || owned
+ if pack := s.storyCatalog.Packs[id]; pack.Type == 0 && pack.BuyPrice == 0 {
+ _, entered := s.collection.Grant(packEntryIdentity(id))
+ purchased = purchased || entered || played[id]
+ }
}
if purchased {
row = wire.AppendVarint(row, 8, 1)
@@ -825,6 +836,13 @@ func (s *Service) handlePackDocking(ctx command.Context, path string, request []
identity := packJamIdentity(packID)
if path == "/PackPreviewInfo" {
var response []byte
+ titles, err := s.questTitleInfo(packID)
+ if err != nil {
+ return 0, nil, true, err
+ }
+ for _, title := range titles {
+ response = wire.AppendBytes(response, 2, title)
+ }
if active := s.firstUnclearedQuestFor(packID); active != 0 {
quest := wire.AppendVarint(nil, 1, uint64(active))
quest = wire.AppendVarint(quest, 6, uint64(packID))
@@ -931,6 +949,11 @@ func (s *Service) enterEventFieldPack(ctx command.Context, pack gamedata.EventFi
position = saved.RawJSON
}
response := wire.AppendString(nil, 4, position)
+ exploration, err := s.mapExplorationWire(ctx, pack.ID)
+ if err != nil {
+ return 0, nil, true, err
+ }
+ response = append(response, exploration...)
buffs, err := s.fieldBuffInfo(ctx)
if err != nil {
return 0, nil, true, err
@@ -969,6 +992,19 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int,
}
}
switch path {
+ case "/PackSubQuestClearInfo":
+ return s.packSubQuestClearInfo(request)
+ case "/ReputationInfo":
+ return s.reputationInfo(ctx, request)
+ case "/QuestImmortalReset":
+ if seq, found, err := wire.Varint(request, 1); err != nil || !found || seq == 0 {
+ return 70, nil, true, ErrInvalidRequest
+ }
+ return 70, nil, true, fmt.Errorf("world: immortal quest difficulty is unavailable in the current design")
+ case "/QuestMaxClearInfo":
+ return s.questMaxClearInfo(request)
+ case "/ActiveMap":
+ return s.handleActiveMap(ctx, request)
case "/StatueObjectReward":
return s.handleStatueReward(ctx, request)
case "/TimePause":
@@ -1110,13 +1146,20 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int,
if err := s.ResumeFieldTime(ctx); err != nil {
return 0, nil, true, err
}
- if s.battleActive != nil && s.battleActive(ctx) {
- return 0, nil, true, fmt.Errorf("%w: active battle", ErrInvalidRequest)
- }
pack, err := requestPack(request)
if err != nil {
return 0, nil, true, err
}
+ activeBattle := s.battleActive != nil && s.battleActive(ctx)
+ if activeBattle {
+ current, err := s.CurrentPackID(ctx)
+ if err != nil {
+ return 0, nil, true, err
+ }
+ if pack != current {
+ return 0, nil, true, fmt.Errorf("%w: cannot change pack during active battle", ErrInvalidRequest)
+ }
+ }
if eventPack, found, err := s.resolveEventFieldPack(ctx, pack); err != nil {
return 0, nil, true, err
} else if found {
@@ -1128,6 +1171,9 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int,
}
body = append(body, extra...)
}
+ if e == nil && activeBattle {
+ body = wire.AppendVarint(body, 17, 1)
+ }
return code, body, handled, e
}
if !s.packUnlocked(ctx, pack) {
@@ -1141,9 +1187,11 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int,
if e != nil {
return 0, nil, true, e
}
- v.Run = skyWayRun{Generation: v.Run.Generation}
- if e = s.skyway.save(ctx, v); e != nil {
- return 0, nil, true, e
+ if !activeBattle {
+ v.Run = skyWayRun{Generation: v.Run.Generation}
+ if e = s.skyway.save(ctx, v); e != nil {
+ return 0, nil, true, e
+ }
}
}
if active := s.firstUnclearedQuestFor(pack); active != 0 {
@@ -1155,6 +1203,9 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int,
if err != nil {
return 0, nil, true, err
}
+ if activeBattle {
+ response = wire.AppendVarint(response, 17, 1)
+ }
if s.talentPackInfo != nil {
extra, e := s.talentPackInfo(ctx, pack)
if e != nil {
@@ -1165,6 +1216,11 @@ func (s *Service) Handle(ctx command.Context, path string, request []byte) (int,
if err := s.state.SetActivePackID(ctx, pack); err != nil {
return 0, nil, true, err
}
+ if story := s.storyCatalog.Packs[pack]; story.Type == 0 && story.BuyPrice == 0 && s.collection != nil {
+ if err := s.collection.RecordGrantMarker(ctx, packEntryIdentity(pack)); err != nil {
+ return 0, nil, true, err
+ }
+ }
s.setCurrentPack(pack)
return 5, response, true, nil
case "/QuestClear":
diff --git a/go/internal/server/domain/world/quest_completion.go b/go/internal/server/domain/world/quest_completion.go
new file mode 100644
index 0000000..81a2199
--- /dev/null
+++ b/go/internal/server/domain/world/quest_completion.go
@@ -0,0 +1,68 @@
+package world
+
+import (
+ "slices"
+
+ "bd2server/internal/server/protocol/wire"
+)
+
+func (s *Service) questMaxClearInfo(request []byte) (int, []byte, bool, error) {
+ if seq, found, err := wire.Varint(request, 1); err != nil || !found || seq == 0 {
+ return 137, nil, true, ErrInvalidRequest
+ }
+ maxima := make(map[int]int, len(s.packs))
+ for pack := range s.packs {
+ maxima[pack] = 0
+ }
+ if s.storyCatalog != nil {
+ for pack := range s.storyCatalog.Packs {
+ maxima[pack] = 0
+ }
+ }
+ for _, quest := range s.state.AllClearedQuests() {
+ maxima[quest.PackID] = max(maxima[quest.PackID], quest.QuestID)
+ }
+ ids := make([]int, 0, len(maxima))
+ for id := range maxima {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ var out []byte
+ for _, pack := range ids {
+ row := wire.AppendVarint(nil, 1, uint64(pack))
+ if maxima[pack] != 0 {
+ row = wire.AppendVarint(row, 2, uint64(maxima[pack]))
+ }
+ out = wire.AppendBytes(out, 1, row)
+ }
+ return 137, out, true, nil
+}
+
+func (s *Service) questTitleInfo(pack int) ([][]byte, error) {
+ if s.storyCatalog == nil {
+ return nil, nil
+ }
+ if _, found := s.storyCatalog.Packs[pack]; !found {
+ return nil, nil
+ }
+ titles, err := s.presentationSource.QuestTitles(pack)
+ if err != nil {
+ return nil, err
+ }
+ cleared := s.state.AllClearedQuests()
+ var rows [][]byte
+ for _, title := range titles {
+ highest := 0
+ for _, quest := range cleared {
+ if quest.PackID == pack && quest.QuestID >= title.FirstQuest && quest.QuestID <= title.LastQuest {
+ highest = max(highest, quest.QuestID)
+ }
+ }
+ row := wire.AppendVarint(nil, 1, uint64(title.ID))
+ if highest != 0 {
+ row = wire.AppendVarint(row, 2, uint64(highest))
+ }
+ rows = append(rows, row)
+ }
+ return rows, nil
+}
diff --git a/go/internal/server/domain/world/quest_preview.go b/go/internal/server/domain/world/quest_preview.go
new file mode 100644
index 0000000..232b158
--- /dev/null
+++ b/go/internal/server/domain/world/quest_preview.go
@@ -0,0 +1,64 @@
+package world
+
+import (
+ "encoding/binary"
+ "math"
+
+ "bd2server/internal/server/protocol/wire"
+)
+
+func (s *Service) packSubQuestClearInfo(request []byte) (int, []byte, bool, error) {
+ seq, found, err := wire.Varint(request, 1)
+ if err != nil || !found || seq == 0 || seq > math.MaxInt32 {
+ return 227, nil, true, ErrInvalidRequest
+ }
+ var packs []int
+ seen := map[int]bool{}
+ err = wire.Walk(request, func(f wire.Field) error {
+ if f.Number != 2 {
+ return nil
+ }
+ if f.Type != 0 && f.Type != 2 {
+ return ErrInvalidRequest
+ }
+ for raw := f.Value; len(raw) > 0; {
+ id, n := binary.Uvarint(raw)
+ if n <= 0 || id == 0 || id > math.MaxInt32 || len(packs) >= 512 {
+ return ErrInvalidRequest
+ }
+ raw = raw[n:]
+ if !seen[int(id)] {
+ seen[int(id)] = true
+ packs = append(packs, int(id))
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return 227, nil, true, err
+ }
+ var response []byte
+ for _, id := range packs {
+ if s.storyCatalog == nil {
+ return 227, nil, true, ErrInvalidRequest
+ }
+ pack, ok := s.storyCatalog.Packs[id]
+ if !ok {
+ return 227, nil, true, ErrInvalidRequest
+ }
+ titles, err := s.presentationSource.QuestTitles(id)
+ if err != nil {
+ return 227, nil, true, err
+ }
+ var count uint64
+ for _, title := range titles {
+ if pack.Quests[title.LastQuest].Type == 1 && s.state.QuestCleared(title.LastQuest, id, 0) {
+ count++
+ }
+ }
+ row := wire.AppendVarint(nil, 1, uint64(id))
+ row = wire.AppendVarint(row, 2, count)
+ response = wire.AppendBytes(response, 1, row)
+ }
+ return 227, response, true, nil
+}
diff --git a/go/internal/server/domain/world/side_quest_chain_test.go b/go/internal/server/domain/world/side_quest_chain_test.go
index 86a1143..2950d18 100644
--- a/go/internal/server/domain/world/side_quest_chain_test.go
+++ b/go/internal/server/domain/world/side_quest_chain_test.go
@@ -84,7 +84,8 @@ func TestForestSideQuestCompletionSurvivesPackEntry(t *testing.T) {
t.Fatal(err)
}
service := &Service{seed: Seed{PackID: 1}, activePack: 1, state: state, wallet: wallet, inventory: inventory,
- storyCatalog: catalog, collection: collection, questCostumes: questCostumes}
+ storyCatalog: catalog, collection: collection, questCostumes: questCostumes,
+ presentationSource: gamedata.NewSource(versions.Resolve("data/resources/GameData"), versions.GameDataVersion)}
service.attachFieldMonsterDesign(gamedata.NewSource(versions.Resolve("data/resources/GameData"), versions.GameDataVersion))
if err := service.AttachFieldMonsterState(stateio.RootStore{}); err != nil {
t.Fatal(err)
@@ -172,7 +173,20 @@ func TestForestSideQuestCompletionSurvivesPackEntry(t *testing.T) {
}
})
run(func(ctx command.Context, service *Service) {
- rows := service.activeSideQuestWires(1)
+ preview := handle(ctx, service, "/PackSubQuestClearInfo", wire.AppendBytes(wire.AppendVarint(nil, 1, 1), 2, []byte{1}))
+ rows, err := nestedMessages(preview, 1)
+ if err != nil || len(rows) != 1 {
+ t.Fatal("side-story menu lost the requested chapter")
+ }
+ count, _, err := wire.Varint(rows[0], 2)
+ var completed uint64
+ if step.next == 0 {
+ completed = 1
+ }
+ if err != nil || count != completed {
+ t.Fatal("the chapter must count the finished side story, not its completed intermediate stages or main difficulty")
+ }
+ rows = service.activeSideQuestWires(1)
wantRows := 1
if step.next == 0 {
wantRows = 0
diff --git a/go/internal/server/domain/world/talent_effects.go b/go/internal/server/domain/world/talent_effects.go
index 333346a..51c7d0e 100644
--- a/go/internal/server/domain/world/talent_effects.go
+++ b/go/internal/server/domain/world/talent_effects.go
@@ -1,10 +1,32 @@
package world
import (
+ "bd2server/internal/server/design/gamedata"
"bd2server/internal/server/domain/command"
+ "bd2server/internal/server/domain/roster"
"fmt"
)
+func (s *Service) ApplyTalentWaypoint(ctx command.Context, _ string, _ roster.Character, rule gamedata.TalentUseRule, targets []uint64) ([]byte, error) {
+ pack, _, _, err := s.TalentFieldContext(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if rule.Class != 15 || len(targets) != 1 {
+ return nil, fmt.Errorf("world: waypoint talent requires one destination map")
+ }
+ design, err := s.presentationSource.Waypoint(uint64(pack))
+ if err != nil {
+ return nil, err
+ }
+ for _, point := range design.Points {
+ if point.MapID == targets[0] && s.decks.ActivatedWaypoint(uint64(pack), point.ID) && (len(rule.Values) > 0 && rule.Values[0] != 0 || point.SafeArea) {
+ return nil, nil
+ }
+ }
+ return nil, fmt.Errorf("world: waypoint talent destination unavailable pack=%d map=%d level=%d", pack, targets[0], rule.Level)
+}
+
func (s *Service) AttachTalentPackInfo(source func(ctx command.Context, _ int) ([]byte, error)) {
s.talentPackInfo = source
}
diff --git a/go/internal/server/gateway/session/request_error.go b/go/internal/server/gateway/session/request_error.go
new file mode 100644
index 0000000..764c157
--- /dev/null
+++ b/go/internal/server/gateway/session/request_error.go
@@ -0,0 +1,115 @@
+package session
+
+import (
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/runtime/player"
+ "errors"
+ "fmt"
+ "strings"
+)
+
+func rejectedRequestError(account string, requests []player.Request, cause error) error {
+ var failed *command.RequestError
+ if errors.As(cause, &failed) {
+ for _, request := range requests {
+ sequence, _, _ := wire.Varint(request.Body, 1)
+ if request.Path == failed.Path && sequence == failed.Sequence {
+ return fmt.Errorf("account_id=%s request={%s}: %w", account, requestErrorContext(request, true), cause)
+ }
+ }
+ }
+ const limit = 4
+ contexts := make([]string, 0, min(len(requests), limit))
+ for _, request := range requests[:min(len(requests), limit)] {
+ contexts = append(contexts, requestErrorContext(request, len(requests) == 1))
+ }
+ return fmt.Errorf("account_id=%s request_count=%d requests=[%s]: %w", account, len(requests), strings.Join(contexts, "; "), cause)
+}
+
+type diagnosticField struct {
+ number int
+ name string
+}
+
+func requestErrorContext(request player.Request, includeFields bool) string {
+ sequence, _, _ := wire.Varint(request.Body, 1)
+ path := request.Path
+ if len(path) > 80 || strings.ContainsAny(path, "\r\n\t") {
+ path = "invalid-route"
+ }
+ context := fmt.Sprintf("path=%s seq=%d", path, sequence)
+ if !includeFields {
+ return context
+ }
+ var fields []diagnosticField
+ switch request.Path {
+ case "/MissionUpdate":
+ count := 0
+ _ = wire.Walk(request.Body, func(field wire.Field) error {
+ if field.Number != 2 || field.Type != 2 {
+ return nil
+ }
+ if count < 3 {
+ context += " mission={" + numericErrorFields(field.Value, []diagnosticField{{1, "group_id"}, {2, "mission_id"}, {3, "value"}, {4, "event_id"}}) + "}"
+ }
+ count++
+ return nil
+ })
+ return context + fmt.Sprintf(" mission_count=%d", count)
+ case "/MissionClear":
+ fields = []diagnosticField{{3, "group_type"}, {4, "group_id"}, {5, "mission_id"}, {6, "event_id"}}
+ case "/PassReward":
+ fields = []diagnosticField{{2, "all"}, {3, "pass_id"}, {4, "level_id"}, {5, "reward_type"}}
+ case "/PassBuy":
+ fields = []diagnosticField{{2, "pass_id"}, {3, "buy_type"}}
+ case "/FriendshipSpecialEpisodeClear":
+ fields = []diagnosticField{{2, "group_id"}, {3, "episode_id"}}
+ case "/FriendshipGift":
+ fields = []diagnosticField{{2, "costume_id"}}
+ case "/FriendshipCounseling":
+ fields = []diagnosticField{{2, "costume_id"}, {3, "session_id"}, {4, "selection"}, {5, "quick"}}
+ case "/QuestUpdate", "/QuestClear":
+ fields = []diagnosticField{{2, "quest_id"}, {3, "pack_id"}}
+ case "/FieldObjectReward":
+ fields = []diagnosticField{{2, "pack_id"}, {3, "group_id"}, {4, "object_id"}}
+ case "/FieldObjectResearch":
+ fields = []diagnosticField{{2, "pack_id"}, {3, "object_id"}}
+ case "/SaveUserPosition", "/PackInGameInfo":
+ fields = []diagnosticField{{2, "pack_id"}}
+ case "/BattleEnter":
+ fields = []diagnosticField{{2, "group_id"}, {3, "monster_id"}, {4, "battle_deck"}, {5, "battle_mode"}, {6, "monster_hunt_id"}}
+ case "/BattleStart", "/BattleRetry":
+ fields = []diagnosticField{{2, "battle_index"}}
+ case "/BattleEnd":
+ fields = []diagnosticField{{2, "battle_result"}, {4, "pack_id"}}
+ case "/BattleRecordInfo", "/BattleRecordSave":
+ fields = []diagnosticField{{2, "battle_mode"}, {3, "content_id"}}
+ case "/GachaBuy":
+ fields = []diagnosticField{{2, "gacha_id"}, {3, "buy_type"}}
+ case "/CashShopBuy":
+ fields = []diagnosticField{{3, "group_id"}, {6, "event_schedule_id"}}
+ case "/CharLevelUp":
+ fields = []diagnosticField{{2, "character_index"}}
+ case "/UseRandomBox":
+ fields = []diagnosticField{{2, "item_index"}, {3, "use_count"}}
+ case "/UseResourceItem":
+ fields = []diagnosticField{{2, "item_index"}, {3, "use_count"}, {4, "selection"}}
+ }
+ if values := numericErrorFields(request.Body, fields); values != "" {
+ context += " " + values
+ }
+ return context
+}
+
+// Only named scalar fields from the current client protocol enter diagnostics.
+func numericErrorFields(body []byte, fields []diagnosticField) string {
+ values := make([]string, 0, len(fields))
+ for _, field := range fields {
+ value, present, err := wire.Varint(body, field.number)
+ if err == nil && present {
+ values = append(values, fmt.Sprintf("%s=%d", field.name, value))
+ }
+ }
+ return strings.Join(values, " ")
+}
diff --git a/go/internal/server/gateway/session/request_error_test.go b/go/internal/server/gateway/session/request_error_test.go
new file mode 100644
index 0000000..e2d6400
--- /dev/null
+++ b/go/internal/server/gateway/session/request_error_test.go
@@ -0,0 +1,58 @@
+package session
+
+import (
+ "bd2server/internal/server/domain/command"
+ "bd2server/internal/server/protocol/wire"
+ "bd2server/internal/server/runtime/player"
+ "errors"
+ "strings"
+ "testing"
+)
+
+func TestRejectedRequestContextIdentifiesFailedBatchItemWithoutPayload(t *testing.T) {
+ secret := "private-receipt-do-not-log"
+ mission := wire.AppendVarint(nil, 1, 303)
+ mission = wire.AppendVarint(mission, 2, 3038)
+ mission = wire.AppendVarint(mission, 3, 1)
+ mission = wire.AppendVarint(mission, 4, 900)
+ mission = wire.AppendString(mission, 99, secret)
+ body := wire.AppendBytes(wire.AppendVarint(nil, 1, 72), 2, mission)
+ gameError := &command.GameError{PacketCode: 1, ErrorType: 2, Message: "unavailable"}
+ failure := &command.RequestError{Path: "/MissionUpdate", Sequence: 72, Cause: gameError}
+ result := rejectedRequestError("owner", []player.Request{
+ {Path: "/CashShopBuy", Body: wire.AppendString(wire.AppendVarint(nil, 1, 71), 7, secret)},
+ {Path: "/MissionUpdate", Body: body},
+ }, failure)
+ message := result.Error()
+ for _, want := range []string{"account_id=owner", "path=/MissionUpdate seq=72", "group_id=303", "mission_id=3038", "event_id=900", "value=1"} {
+ if !strings.Contains(message, want) {
+ t.Errorf("diagnostic %q missing %q", message, want)
+ }
+ }
+ if strings.Contains(message, secret) || strings.Contains(message, "/CashShopBuy") {
+ t.Fatalf("diagnostic included an unrelated request or payload: %s", message)
+ }
+ var preserved *command.GameError
+ if !errors.Is(result, failure) || !errors.As(result, &preserved) || preserved != gameError {
+ t.Fatal("diagnostic wrapping changed error identity or game error classification")
+ }
+}
+
+func TestRejectedRequestContextBoundsBatchAndMissionSummaries(t *testing.T) {
+ requests := make([]player.Request, 6)
+ for i := range requests {
+ requests[i] = player.Request{Path: "/QuestUpdate", Body: wire.AppendVarint(nil, 1, uint64(i+1))}
+ }
+ message := rejectedRequestError("owner", requests, errors.New("commit failed")).Error()
+ if !strings.Contains(message, "request_count=6") || strings.Count(message, "path=") != 4 || strings.Contains(message, "seq=5") {
+ t.Fatalf("unbounded batch diagnostic: %s", message)
+ }
+ body := wire.AppendVarint(nil, 1, 10)
+ for i := range 5 {
+ body = wire.AppendBytes(body, 2, wire.AppendVarint(nil, 2, uint64(i+1)))
+ }
+ message = requestErrorContext(player.Request{Path: "/MissionUpdate", Body: body}, true)
+ if strings.Count(message, "mission={") != 3 || !strings.Contains(message, "mission_count=5") {
+ t.Fatalf("unbounded mission diagnostic: %s", message)
+ }
+}
diff --git a/go/internal/server/gateway/session/server.go b/go/internal/server/gateway/session/server.go
index f398ed8..c5039ea 100644
--- a/go/internal/server/gateway/session/server.go
+++ b/go/internal/server/gateway/session/server.go
@@ -2,6 +2,7 @@
package session
import (
+ "bd2server/internal/common/util"
"bd2server/internal/server/domain/command"
"bd2server/internal/server/gateway/transport"
"bd2server/internal/server/protocol"
@@ -9,7 +10,6 @@ import (
"bd2server/internal/server/protocol/wire"
"bd2server/internal/server/runtime/player"
"context"
- "crypto/rand"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
@@ -122,7 +122,7 @@ func (s *Server) dispatchRaw(ctx context.Context, path string, body []byte, cook
return rejection, encodeErr
}
}
- return transport.RawReply{}, err
+ return transport.RawReply{}, rejectedRequestError(game.accountID, requests, err)
}
if len(response.Responses) != len(requests) {
return transport.RawReply{}, errors.New("player response count does not match command")
@@ -301,25 +301,25 @@ func (s *Server) authorize(cookie string) (*gameSession, error) {
return &gameSession{key: append([]byte(nil), game.key...), accountID: game.accountID, id: game.id, expiresAt: game.expiresAt, lastUsed: game.lastUsed, generation: game.generation}, nil
}
func newGameSession(accountID string, now time.Time, ttl time.Duration) (*gameSession, string, error) {
- keyBytes := make([]byte, 16)
- if _, err := rand.Read(keyBytes); err != nil {
+ key, err := util.RandomHex(16)
+ if err != nil {
return nil, "", fmt.Errorf("create game session key: %w", err)
}
- tokenBytes := make([]byte, 24)
- if _, err := rand.Read(tokenBytes); err != nil {
+ token, err := util.RandomHex(24)
+ if err != nil {
return nil, "", fmt.Errorf("create game session token: %w", err)
}
- idBytes := make([]byte, 12)
- if _, err := rand.Read(idBytes); err != nil {
+ id, err := util.RandomHex(12)
+ if err != nil {
return nil, "", fmt.Errorf("create login request identity: %w", err)
}
return &gameSession{
- key: []byte(hex.EncodeToString(keyBytes)),
+ key: []byte(key),
accountID: accountID,
- id: hex.EncodeToString(idBytes),
+ id: id,
expiresAt: now.Add(ttl),
lastUsed: now,
- }, hex.EncodeToString(tokenBytes) + "|1", nil
+ }, token + "|1", nil
}
func sessionTokenKey(token string) [sha256.Size]byte { return sha256.Sum256([]byte(token)) }
diff --git a/go/internal/server/gateway/transport/http.go b/go/internal/server/gateway/transport/http.go
index 4daae08..5639042 100644
--- a/go/internal/server/gateway/transport/http.go
+++ b/go/internal/server/gateway/transport/http.go
@@ -142,6 +142,7 @@ type HTTP struct {
CommerceManifest func() any
RealtimeTickets http.Handler
StoryCheckpoints http.Handler
+ SpineRecordings http.Handler
// Console is the built-in administration website below /admin/.
Console http.Handler
// Compatibility is the launcher's view of what this server requires.
@@ -184,6 +185,9 @@ func (h HTTP) Handler() http.Handler {
if h.StoryCheckpoints != nil {
mux.Handle("/client/story-checkpoint", h.withCompatibility(h.withAvailability(h.StoryCheckpoints)))
}
+ if h.SpineRecordings != nil {
+ mux.Handle("GET /client/spine-recordings/", h.withAvailability(h.SpineRecordings))
+ }
if h.RealtimeTickets != nil {
mux.Handle("/client/realtime-ticket", h.withCompatibility(h.withAvailability(h.RealtimeTickets)))
}
diff --git a/go/internal/server/platform/updates/schedules.go b/go/internal/server/platform/updates/schedules.go
index 4fb3d8a..b1de44e 100644
--- a/go/internal/server/platform/updates/schedules.go
+++ b/go/internal/server/platform/updates/schedules.go
@@ -1,6 +1,7 @@
package updates
import (
+ "bd2server/internal/common/util"
"context"
"errors"
"fmt"
@@ -119,7 +120,7 @@ func verifyScheduleFiles(root string, s release.Schedules) error {
if !info.Mode().IsRegular() || info.Size() != f.Size {
return fmt.Errorf("schedule %s is not a regular file of the signed size", f.Name)
}
- sum, err := release.HashFile(path)
+ sum, err := util.SHA256File(path)
if err != nil {
return err
}
@@ -208,7 +209,7 @@ func bundledScheduleID(root, game, gameData string) (string, error) {
if err != nil {
return "", err
}
- digest, err := release.HashFile(path)
+ digest, err := util.SHA256File(path)
if err != nil {
return "", err
}
diff --git a/go/internal/server/platform/updates/switch.go b/go/internal/server/platform/updates/switch.go
index 407bbc6..463532b 100644
--- a/go/internal/server/platform/updates/switch.go
+++ b/go/internal/server/platform/updates/switch.go
@@ -1,6 +1,7 @@
package updates
import (
+ "bd2server/internal/common/util"
"context"
"crypto/sha256"
"encoding/hex"
@@ -515,7 +516,7 @@ func copyVerified(source, target string) error {
if err := out.Close(); err != nil {
return err
}
- copied, err := release.HashFile(target)
+ copied, err := util.SHA256File(target)
if err != nil {
return err
}
diff --git a/go/internal/server/protocol/defaults/bootstrap.go b/go/internal/server/protocol/defaults/bootstrap.go
deleted file mode 100644
index f93a416..0000000
--- a/go/internal/server/protocol/defaults/bootstrap.go
+++ /dev/null
@@ -1,16 +0,0 @@
-package feature
-
-import "bd2server/internal/server/protocol/wire"
-
-// initialResponses are locally constructed, typed defaults for the
-// new-player account. These do not reuse recorded response bytes. Stateful
-// entities (inventory, characters, quests, decks) are deliberately excluded.
-func initialResponse(path string) (int, []byte, bool) {
- switch path {
- case "/AvatarInfo":
- return 467, wire.AppendBytes(nil, 1, nil), true
- case "/GuildRaidSeasonReward":
- return 310, wire.AppendBytes(nil, 1, nil), true
- }
- return 0, nil, false
-}
diff --git a/go/internal/server/protocol/defaults/feature.go b/go/internal/server/protocol/defaults/feature.go
index c9c9dc0..59e6b89 100644
--- a/go/internal/server/protocol/defaults/feature.go
+++ b/go/internal/server/protocol/defaults/feature.go
@@ -1,8 +1,4 @@
-// Package feature contains deliberately small, stateless protocol handlers.
-//
-// These endpoints were observed to return an empty protobuf for a new local
-// account. Keeping that fact here (rather than treating every unknown route
-// as successful) lets the session dispatcher remain fail-closed.
+// Package feature handles the three intentionally stateless protocol endpoints.
package feature
import (
@@ -17,29 +13,10 @@ import (
// ErrInvalidRequest means a known endpoint was sent a malformed request.
var ErrInvalidRequest = errors.New("feature: invalid protobuf request")
-// emptyResponses is the stateless subset of the new-player batch whose
-// successful response protobuf has zero bytes. Stateful routes leave this map
-// as soon as their owning domain persists them. Packet codes are protocol
-// values, not ordinals derived from the request or response order.
var emptyResponses = map[string]int{
- "/AvatarShopWishListInfo": 470,
- "/CafeteriaInfo": 351,
- "/CommunityRewardInfo": 289,
- "/DailyStoryInfo": 538,
- "/DatingInfo": 361,
- "/EquipPresetInfo": 253,
- "/EvilCastleDailyRewardState": 441,
- "/EvilCastleTowerInfo": 200,
- "/FishingCollectionInfo": 465,
- "/FishingTrapInfo": 457,
- "/GuildInitInfo": 332,
- "/IdCardPresetInfo": 450,
- "/LifeUserInfo": 594,
- "/PersonalInfo": 199,
- "/QuestMaxClearInfo": 137,
- "/SpineInteractionAchievementInfo": 532,
- "/TotalWarRewardState": 252,
- "/TutorialInfo": 101,
+ "/PersonalInfo": 199,
+ "/BalanceVersionCheck": 186,
+ "/UpdateAgeGate": 0,
}
// Handle recognizes only audited, stateless empty-response endpoints. The
@@ -50,16 +27,7 @@ var emptyResponses = map[string]int{
func Handle(ctx command.Context, path string, request []byte) (packetCode int, proto []byte, ok bool, err error) {
packetCode, ok = emptyResponses[path]
if !ok {
- packetCode, proto, ok = initialResponse(path)
- }
- if !ok {
- packetCode, ok = standaloneDefaults[path]
- }
- if !ok {
- packetCode, ok = commandSuccess[path]
- if !ok {
- return 0, nil, false, nil
- }
+ return 0, nil, false, nil
}
sequence, present, walkErr := wire.Varint(request, 1)
if walkErr != nil || !present || sequence == 0 {
diff --git a/go/internal/server/protocol/defaults/standalone.go b/go/internal/server/protocol/defaults/standalone.go
deleted file mode 100644
index 23fcd71..0000000
--- a/go/internal/server/protocol/defaults/standalone.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package feature
-
-// standaloneDefaults are native local-server defaults for optional query
-// features. An empty protobuf means the local account currently has no rows or
-// no active server schedule; it is not copied from a captured response.
-var standaloneDefaults = map[string]int{
- "/BalanceVersionCheck": 186,
- "/EquipInfo": 34,
- "/MissionInfo": 118,
- "/FishingItemInfo": 459,
- // No PvP decks, battle history or one-time reward claims have been saved.
- // Their repeated-only protobufs encode these account states as empty, and
- // the client's callbacks continue the arena-lobby entry sequence.
- "/PvpBattleDeckInfo": 87,
- "/PvpBattleHistory": 97,
- "/PvpBattleOnceRewardInfo": 277,
-}
-
-// commandSuccess contains idempotent local mutations whose response type is
-// canonically empty. Domain persistence can be added without changing their
-// protocol contract. Core progress commands are handled by session first.
-var commandSuccess = map[string]int{
- "/UpdateAgeGate": 0,
- "/ActiveMap": 0,
- "/CostumeUse": 41,
- "/BattleExit": 388,
-}
diff --git a/go/internal/server/protocol/login/login.go b/go/internal/server/protocol/login/login.go
index 2835a44..61e1632 100644
--- a/go/internal/server/protocol/login/login.go
+++ b/go/internal/server/protocol/login/login.go
@@ -20,6 +20,7 @@ var (
// deliberately absent. ResponseFields contains the remaining top-level
// protobuf fields (such as client-notification state), never an HTTP envelope.
type LoginSeed struct {
+ totalWarSlots func(command.Context) (uint64, error)
guildRaidSlots func(command.Context) (uint64, error)
fishing func() FishingState
Version string
@@ -81,6 +82,14 @@ func (s *LoginSeed) AttachGuildRaidSlots(read func(command.Context) (uint64, err
return nil
}
+func (s *LoginSeed) AttachTotalWarSlots(read func(command.Context) (uint64, error)) error {
+ if read == nil {
+ return errors.New("account: missing total war preset provider")
+ }
+ s.totalWarSlots = read
+ return nil
+}
+
type FishingState struct{ AP, FishSlots, RodSlots, ItemSlots uint64 }
func (s *LoginSeed) AttachFishing(read func() FishingState) error {
diff --git a/go/internal/server/protocol/login/protocol_adapter.go b/go/internal/server/protocol/login/protocol_adapter.go
index 446a2c5..b99a519 100644
--- a/go/internal/server/protocol/login/protocol_adapter.go
+++ b/go/internal/server/protocol/login/protocol_adapter.go
@@ -308,6 +308,19 @@ func (s *LoginSeed) Login(ctx command.Context, request, sessionKey []byte) ([]by
return nil, err
}
}
+ if s.totalWarSlots != nil {
+ value, err := s.totalWarSlots(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if value > math.MaxInt32 {
+ return nil, errors.New("account: total war slots exceed protocol range")
+ }
+ user, _, err = wire.ReplaceVarint(user, 33, value)
+ if err != nil {
+ return nil, err
+ }
+ }
if s.fishing != nil {
state := s.fishing()
for i, value := range []uint64{state.AP, state.FishSlots, state.RodSlots, state.ItemSlots} {
diff --git a/go/internal/server/runtime/delivery/dispatcher.go b/go/internal/server/runtime/delivery/dispatcher.go
index c9f2787..c914493 100644
--- a/go/internal/server/runtime/delivery/dispatcher.go
+++ b/go/internal/server/runtime/delivery/dispatcher.go
@@ -1,10 +1,9 @@
package delivery
import (
+ "bd2server/internal/common/util"
"context"
- "crypto/rand"
"crypto/sha256"
- "encoding/hex"
"encoding/json"
"errors"
"fmt"
@@ -49,12 +48,12 @@ func New(router Router, consumer Consumer, discovery Discovery) (*Dispatcher, er
if router == nil || consumer == nil || discovery == nil {
return nil, errors.New("delivery requires player routing, consumer and discovery")
}
- var nonce [16]byte
- if _, err := rand.Read(nonce[:]); err != nil {
+ nonce, err := util.RandomHex(16)
+ if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
- d := &Dispatcher{router: router, consumer: consumer, discovery: discovery, queue: make(chan string, 128), scheduled: map[string]bool{}, ctx: ctx, cancel: cancel, done: make(chan struct{}), session: "delivery:" + hex.EncodeToString(nonce[:])}
+ d := &Dispatcher{router: router, consumer: consumer, discovery: discovery, queue: make(chan string, 128), scheduled: map[string]bool{}, ctx: ctx, cancel: cancel, done: make(chan struct{}), session: "delivery:" + nonce}
var workers sync.WaitGroup
workers.Go(d.scan)
for range 4 {
diff --git a/go/internal/server/runtime/player/runtime.go b/go/internal/server/runtime/player/runtime.go
index a7d4b5e..029033c 100644
--- a/go/internal/server/runtime/player/runtime.go
+++ b/go/internal/server/runtime/player/runtime.go
@@ -51,6 +51,7 @@ const (
ReadRoomProfile
CloseExpiredRaid
StoryCheckpoint
+ ReadSpineRecording
)
type SystemRequest struct {
@@ -202,7 +203,7 @@ func (r *Runtime) Submit(ctx context.Context, c Command) (*Future, error) {
if c.Identity.SessionID == "" || c.Identity.RequestID == "" || (len(c.Requests) == 0) == (c.System == nil) {
return nil, errors.New("command requires session, request identity and requests")
}
- if c.System != nil && (c.System.Kind < ReadOutbox || c.System.Kind > StoryCheckpoint || len(c.LoginSessionKey) != 0) {
+ if c.System != nil && (c.System.Kind < ReadOutbox || c.System.Kind > ReadSpineRecording || len(c.LoginSessionKey) != 0) {
return nil, errors.New("invalid player system command")
}
size := commandBytes(c)
diff --git a/go/internal/server/runtime/room/manager.go b/go/internal/server/runtime/room/manager.go
index 9635925..c4f00a2 100644
--- a/go/internal/server/runtime/room/manager.go
+++ b/go/internal/server/runtime/room/manager.go
@@ -1,9 +1,8 @@
package room
import (
+ "bd2server/internal/common/util"
"context"
- "crypto/rand"
- "encoding/hex"
"errors"
"fmt"
"slices"
@@ -130,11 +129,11 @@ func New(config Config, rules Rules) (*Manager, error) {
}
func randomID() string {
- var value [16]byte
- if _, err := rand.Read(value[:]); err != nil {
+ value, err := util.RandomHex(16)
+ if err != nil {
panic(err)
}
- return hex.EncodeToString(value[:])
+ return value
}
func memberKey(p Principal, k Kind) string { return p.AccountID + ":" + string(k) }
func validPrincipal(p Principal) bool {
diff --git a/tools/server/bd2-host.sh b/tools/server/bd2-host.sh
index 74baad6..963be57 100755
--- a/tools/server/bd2-host.sh
+++ b/tools/server/bd2-host.sh
@@ -1,14 +1,16 @@
#!/bin/sh
# bd2-host.sh: everything a Docker host does for bd2server, in one place.
#
-# setup [COMMIT] first install and deploy (one-click; safe to rerun)
-# install prepare directories, secrets, source checkout and the
+# setup [SOURCE] first install and deploy local source (safe to rerun)
+# setup --image REF first install and deploy a Docker image
+# install [SOURCE] prepare directories, secrets, a Compose template and the
# update-handoff units; never replaces existing data
-# deploy [COMMIT] build COMMIT (default: tip of origin/main) from a clean
-# checkout, switch the container and wait until ready
+# deploy [SOURCE] build a source directory (default: /opt/bd2/source),
+# switch the container and wait until ready; no Git needed
+# deploy --image REF deploy an existing local image or pull it if missing
# handoff serve a server-requested update (run by the .path unit)
# rollback start the image that ran before the last switch
-# status show the running image, commit and readiness
+# status show the running image and optional commit
#
# Run as root. Settings come from /etc/bd2/host.conf (KEY=value lines, see
# load_config) and default to a self-contained layout below /opt/bd2.
@@ -75,31 +77,34 @@ lock() {
# --- source -------------------------------------------------------------------
verify_source() {
- [ -d "$SOURCE_DIR/.git" ] || die "no source checkout at $SOURCE_DIR; run install"
+ if [ ! -e "$SOURCE_DIR" ]; then
+ git clone --quiet "$SOURCE_URL" "$SOURCE_DIR" || die 'cannot clone the release source'
+ fi
+ [ -d "$SOURCE_DIR/.git" ] || die "no Git checkout at $SOURCE_DIR for source-based automatic updates"
actual=$(git -C "$SOURCE_DIR" remote get-url --all origin) || die 'cannot read the source origin'
actual=${actual%/}
expected=${SOURCE_URL%/}
[ "${actual%.git}" = "${expected%.git}" ] || die "source origin $actual is not $SOURCE_URL"
- [ -z "$(git -C "$SOURCE_DIR" status --porcelain --untracked-files=all)" ] || die 'the source checkout has local changes'
git -C "$SOURCE_DIR" fetch --quiet --no-tags --prune origin '+refs/heads/*:refs/bd2-update/*' || die 'cannot fetch the source origin'
}
-# resolve_commit prints COMMIT, or the tip of origin/main, after checking it
-# is a published commit: production only runs pushed, versioned code.
+# Automatic updates resolve the commit from the authenticated release request.
resolve_commit() {
- if [ -z "${1:-}" ]; then
- git -C "$SOURCE_DIR" rev-parse --verify 'refs/bd2-update/main^{commit}' || die 'origin has no main branch'
- return
- fi
printf '%s\n' "$1" | grep -Eq '^[0-9a-f]{40}$' || die 'COMMIT must be a full 40-digit commit hash'
[ "$(git -C "$SOURCE_DIR" rev-parse --verify "$1^{commit}" 2>/dev/null)" = "$1" ] || die "$1 is not a commit in the source repository"
- for ref in $(git -C "$SOURCE_DIR" for-each-ref --format='%(refname)' refs/bd2-update/); do
- if git -C "$SOURCE_DIR" merge-base --is-ancestor "$1" "$ref"; then
- printf '%s\n' "$1"
- return
- fi
- done
- die "$1 is not reachable from any published branch"
+ printf '%s\n' "$1"
+}
+
+build_source_image() {
+ source_path=$(realpath "$1") || die 'cannot resolve the source directory'
+ [ -f "$source_path/Dockerfile.server" ] || die "no Dockerfile.server in $source_path"
+ docker build --quiet -f "$source_path/Dockerfile.server" "$source_path"
+}
+
+resolve_image() {
+ docker image inspect --format '{{.Id}}' "$1" 2>/dev/null && return
+ docker pull "$1" >&2 || return 1
+ docker image inspect --format '{{.Id}}' "$1"
}
# build_image COMMIT prints the immutable image ID built from a fresh
@@ -189,13 +194,22 @@ previous_image() {
# --- commands -----------------------------------------------------------------
cmd_install() {
- require docker git jq flock curl nsenter openssl install stat
+ require docker jq flock curl nsenter openssl install stat
docker compose version >/dev/null 2>&1 || die 'the Docker Compose plugin is required'
install -d -m 700 -o root -g root "$BD2_DIR"
- if [ ! -d "$SOURCE_DIR/.git" ]; then
- git clone --quiet "$SOURCE_URL" "$SOURCE_DIR"
+ if [ ! -e "$COMPOSE_FILE" ]; then
+ template=$(dirname "$(readlink -f "$0")")/compose.yaml
+ if [ -n "${1:-}" ]; then
+ template=$1/tools/server/compose.yaml
+ elif [ ! -f "$template" ]; then
+ if [ ! -d "$SOURCE_DIR" ]; then
+ require git
+ git clone --quiet "$SOURCE_URL" "$SOURCE_DIR"
+ fi
+ template=$SOURCE_DIR/tools/server/compose.yaml
+ fi
+ [ -f "$template" ] || die "no Compose template at $template"
fi
- verify_source
install -d -m 700 -o 10001 -g 10001 "$DATA_DIR" "$UPDATES"
install -d -m 755 -o 10001 -g 10001 "$DATA_DIR/config"
if [ -n "$SEED_CONFIG_DIR" ]; then
@@ -214,7 +228,7 @@ cmd_install() {
fi
[ "$(grep -c '^BD2_AUTH_MASTER_KEY=' "$ENV_FILE")" -eq 1 ] || die "$ENV_FILE needs exactly one BD2_AUTH_MASTER_KEY"
if [ ! -e "$COMPOSE_FILE" ]; then
- install -m 644 "$SOURCE_DIR/tools/server/compose.yaml" "$COMPOSE_FILE"
+ install -m 644 "$template" "$COMPOSE_FILE"
log "created $COMPOSE_FILE from the template; review its ports before exposing the server"
fi
if [ "$(readlink -f "$0")" != "$(readlink -f "$SELF" 2>/dev/null || true)" ]; then
@@ -257,14 +271,27 @@ EOF
}
cmd_deploy() {
- require docker git jq flock curl nsenter
+ require docker jq flock curl nsenter
+ mode=source
+ source_path=$SOURCE_DIR
+ case "$#" in
+ 0) ;;
+ 1) [ "$1" != --image ] || die 'usage: deploy --image REF'; source_path=$1 ;;
+ 2) [ "$1" = --image ] || die 'usage: deploy [SOURCE] | deploy --image REF'; mode=image; image_ref=$2 ;;
+ *) die 'usage: deploy [SOURCE] | deploy --image REF' ;;
+ esac
lock
[ ! -f "$UPDATES/docker-request.json" ] && [ ! -f "$UPDATES/docker-request.processing.json" ] ||
die 'a server-requested update is pending; let it finish (or inspect it) before deploying'
- verify_source
- commit=$(resolve_commit "${1:-}")
- log "building $commit"
- target=$(build_image "$commit")
+ if [ "$mode" = image ]; then
+ log "resolving image $image_ref"
+ target=$(resolve_image "$image_ref") || die 'cannot resolve the deployment image'
+ else
+ require realpath
+ log "building local source $source_path"
+ target=$(build_source_image "$source_path") || die 'building the local source failed'
+ fi
+ printf '%s\n' "$target" | grep -Eq '^sha256:[0-9a-f]{64}$' || die 'build did not produce an immutable image ID'
if replaced=$(previous_image); then
old_container=${replaced% *}
remember_previous "${replaced#* }"
@@ -274,7 +301,7 @@ cmd_deploy() {
log "starting $target"
use_image "$target" || die 'switching the container failed'
if ready "$target" "$old_container"; then
- log "deployed $commit; the server is ready"
+ log "deployed $target; the server is ready"
cmd_status
return
fi
@@ -282,6 +309,15 @@ cmd_deploy() {
die "the new container did not become ready; inspect the logs above, then fix forward or run: $SELF rollback"
}
+cmd_setup() {
+ case "$#" in
+ 0|1) cmd_install "$@" ;;
+ 2) [ "$1" = --image ] || die 'usage: setup [SOURCE] | setup --image REF'; cmd_install ;;
+ *) die 'usage: setup [SOURCE] | setup --image REF' ;;
+ esac
+ cmd_deploy "$@"
+}
+
cmd_rollback() {
require docker flock curl nsenter jq
lock
@@ -386,20 +422,19 @@ cmd_handoff() {
[ -z "$fingerprint" ] || printf '%s\n' "$fingerprint" | grep -Eq '^[0-9a-f]{64}$' || fail 'invalid target fingerprint'
image=$(jq -r '.image // ""' "$processing")
migration=$(jq -r '.migration.kind' "$processing")
- for dependency in docker curl nsenter git mktemp stat cp; do
+ for dependency in docker curl nsenter mktemp stat cp; do
command -v "$dependency" >/dev/null || fail "$dependency is required"
done
replaced=$(previous_image) || fail 'expected exactly one existing Compose container with an immutable image'
old_container=${replaced% *}
previous=${replaced#* }
- # The commit must be published even when an immutable image is supplied.
- (verify_source && resolve_commit "$commit" >/dev/null) || fail 'the requested commit is not a published commit of the source repository'
if [ -n "$image" ]; then
printf '%s\n' "$image" | grep -Eq '^[A-Za-z0-9][A-Za-z0-9._:/-]*@sha256:[0-9a-f]{64}$' || fail 'image must be pinned by a sha256 repository digest'
docker pull "$image" >/dev/null || fail 'pulling the requested image failed'
target=$(docker image inspect --format '{{.Id}}' "$image") || fail 'cannot resolve the pulled image ID'
else
+ (require git && verify_source && resolve_commit "$commit" >/dev/null) || fail 'cannot resolve the release source commit'
target=$(build_image "$commit") || fail 'building the requested commit failed'
fi
@@ -437,11 +472,11 @@ load_config
command=${1:-}
[ "$#" -eq 0 ] || shift
case "$command" in
- setup) cmd_install; cmd_deploy "${1:-}" ;;
- install) cmd_install ;;
- deploy) cmd_deploy "${1:-}" ;;
+ setup) cmd_setup "$@" ;;
+ install) [ "$#" -le 1 ] || die 'usage: install [SOURCE]'; cmd_install "$@" ;;
+ deploy) cmd_deploy "$@" ;;
rollback) cmd_rollback ;;
status) cmd_status ;;
handoff) cmd_handoff ;;
- *) sed -n '2,13s/^# \{0,1\}//p' "$0"; exit 2 ;;
+ *) sed -n '2,15s/^# \{0,1\}//p' "$0"; exit 2 ;;
esac